summaryrefslogtreecommitdiff
path: root/src/tools/crossgen/crossgen.cpp
blob: 1c807f5d2185dce84d63e77c3cead93e093d8d13 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//
// TO DO: we currently use raw printf() for output. Maybe we need to pick up something like ngen's Output() handling
// to handle multiple code pages, etc, better.

#include <stdio.h>
#include <fcntl.h>
#include <io.h>

#include <windows.h>
#include <fxver.h>
#include <mscorsvc.h>

#include "palclr.h"

#include <sstring.h>
#include "ex.h"

#include "coregen.h"
#include "consoleargs.h"

// Return values from wmain() in case of error
enum ReturnValues
{
    FAILURE_RESULT = 1,
    CLR_INIT_ERROR = -2,
    ASSEMBLY_NOT_FOUND = -3,
    INVALID_ARGUMENTS = -4
};

#define NumItems(s) (sizeof(s) / sizeof(s[0]))

STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzAppNiPaths, LPCWSTR pwzPdbPath, BOOL fGeneratePDBLinesInfo, LPCWSTR pwzManagedPdbSearchPath, LPCWSTR pwzPlatformWinmdPaths);
STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzOutputFilename=NULL, LPCWSTR pwzPlatformWinmdPaths=NULL, ICorSvcLogger *pLogger = NULL);
void SetSvcLogger(ICorSvcLogger *pCorSvcLogger);
#ifdef FEATURE_CORECLR
void SetMscorlibPath(LPCWSTR wzSystemDirectory);
#endif

/* --------------------------------------------------------------------------- *    
 * Console stuff
 * --------------------------------------------------------------------------- */

void Output(LPCWSTR str)
{
    wprintf(W("%s"), str);
}

void Outputf(LPCWSTR szFormat, ...)
{
    va_list args;
    va_start(args, szFormat);
    vfwprintf(stdout, szFormat, args);
    va_end(args);
}

void OutputErr(LPCWSTR str)
{
    fwprintf(stderr, W("%s"), str);
}

void OutputErrf(LPCWSTR szFormat, ...)
{
    va_list args;
    va_start(args, szFormat);
    vfwprintf(stderr, szFormat, args);
    va_end(args);
}

void ErrorHR(HRESULT hr)
{
    OutputErrf(W("Error: failed to initialize CoreCLR: 0x%08x\n"), hr);
}

void ErrorWin32(DWORD err)
{
    ErrorHR(HRESULT_FROM_WIN32(err));
}

// Some error messages are useless to callers, so make them generic, except in debug builds, where we want as much
// information as possible.

#ifdef _DEBUG
#define ERROR_HR(msg,hr)        Outputf(msg, hr)
#define ERROR_WIN32(msg,err)    Outputf(msg, err)
#else // _DEBUG
#define ERROR_HR(msg,hr)        ErrorHR(hr)
#define ERROR_WIN32(msg,err)    ErrorWin32(err)
#endif // _DEBUG


void PrintLogoHelper()
{
#ifdef FEATURE_CORECLR
    Output(W("Microsoft (R) CoreCLR Native Image "));
#else
    Output(W("Microsoft (R) CLR Native Image "));
#endif
    Outputf(W("Generator - Version %S\n"), VER_FILEVERSION_STR);
    Outputf(W("%S\n"), VER_LEGALCOPYRIGHT_LOGO_STR);
    Output(W("\n"));
}

void PrintUsageHelper()
{
    // Always print the logo when we print the usage, even if they've specified /nologo and we've parsed that already.
    PrintLogoHelper();

    Output(
       W("Usage: crossgen [args] <assembly name>\n")
       W("\n")
       W("    /? or /help          - Display this screen\n")
       W("    /nologo              - Prevents displaying the logo\n")
       W("    @response.rsp        - Process command line arguments from specified\n")
       W("                           response file\n")
#ifdef FEATURE_CORECLR
       W("    /partialtrust        - Assembly will be run in a partial trust domain.\n")
#endif
       W("    /in <file>           - Specifies input filename (optional)\n")
       W("    /out <file>          - Specifies output filename (optional)\n")
#ifdef FEATURE_CORECLR
       W("    /Trusted_Platform_Assemblies <path[;path]>\n")
       W("                         - List of assemblies treated as trusted platform\n")
       W("                         - Cannot be used with Platform_Assemblies_Paths\n")
       W("    /Platform_Resource_Roots <path[;path]>\n")
       W("                         - List of paths containing localized assembly directories\n")
       W("    /App_Paths <path>    - List of paths containing user-application assemblies and resources\n")
#ifndef NO_NGENPDB
       W("    /App_Ni_Paths <path[;path]>\n")
       W("                         - List of paths containing user-application native images\n")
       W("                         - Must be used with /CreatePDB switch\n")
#endif // NO_NGENPDB
#endif // FEATURE_CORECLR

       W("    /Platform_Assemblies_Paths\n")
       W("                         - List of paths containing target platform assemblies\n")
#ifdef FEATURE_CORECLR
       // If Platform_Assemblies_Paths, we will use it to build the TPA list and thus,
       // TPA list cannot be explicitly specified.
       W("                         - Cannot be used with Trusted_Platform_Assemblies\n")
#endif // FEATURE_CORECLR
       
#ifdef FEATURE_COMINTEROP
       W("    /Platform_Winmd_Paths\n")
       W("                         - List of paths containing target platform WinMDs used\n")
       W("                           for emulating RoResolveNamespace\n")
#endif
       W("    /MissingDependenciesOK\n")
       W("                         - Specifies that crossgen should attempt not to fail\n")
       W("                           if a dependency is missing.\n")
#if 0
       W("    /Tuning              - Generate an instrumented image to collect\n")
       W("                           scenario traces, which can be used with ibcmerge.exe\n")
#endif
#ifdef FEATURE_READYTORUN_COMPILER
       W("    /ReadyToRun          - Generate images resilient to the runtime and\n")
       W("                           dependency versions\n")
#endif
#ifdef FEATURE_LEGACYNETCF
       W(" Compatability Modes\n")
       W("    /PreWP8App           - Set the Windows Phone 8 \"Quirks\" mode, namely AppDomainCompatSwitch=\n")
       W("                           WindowsPhone_3.7.0.0 or WindowsPhone_3.8.0.0.\n")
#endif
#ifdef FEATURE_WINMD_RESILIENT
       W(" WinMD Parameters\n")
       W("    /WinMDResilient - Generate images resilient to WinMD dependency changes.\n")
#endif
#ifdef FEATURE_CORECLR
       W(" Size on Disk Parameters\n")
       W("    /NoMetaData     - Do not copy metadata and IL into native image.\n")
#endif // FEATURE_CORECLR
#ifndef NO_NGENPDB
       W(" Debugging Parameters\n")
       W("    /CreatePDB <Dir to store PDB> [/lines [<search path for managed PDB>] ]\n")
       W("        When specifying /CreatePDB, the native image should be created\n")
       W("        first, and <assembly name> should be the path to the NI.")
#elif defined(FEATURE_PERFMAP)
       W(" Debugging Parameters\n")
       W("    /CreatePerfMap <Dir to store perf map>\n")
       W("        When specifying /CreatePerfMap, the native image should be created\n")
       W("        first, and <assembly name> should be the path to the NI.\n")
#endif
       );
}

class CrossgenLogger : public ICorSvcLogger
{
    STDMETHODIMP_(ULONG)    AddRef()  {return E_NOTIMPL;}
    STDMETHODIMP_(ULONG)    Release() {return E_NOTIMPL;}
    STDMETHODIMP            QueryInterface(REFIID riid,void ** ppv)
    {
        if (ppv==0) 
            return E_POINTER;
        
        *ppv = NULL;
        
        if (IsEqualIID(riid, IID_ICorSvcLogger) || IsEqualIID(riid, IID_IUnknown))
        {
            *ppv = this;
            return S_OK;
        }
        else
        {
            return E_NOINTERFACE;
        }
    }

    HRESULT STDMETHODCALLTYPE Log(        
            /*[in] */CorSvcLogLevel logLevel,
            /*[in] */BSTR message
        )
    {
        if (logLevel == LogLevel_Error)
            OutputErr(message);
        else
            Output(message);
        return S_OK;
    }
};

CrossgenLogger                g_CrossgenLogger;

//
// Tests whether szArg, the currently indexed argv matches the specified parameter name, szTestParamName.
// Specify szTestParamName without a switch.  This method handles testing for - and / switches.
//
bool MatchParameter(LPCWSTR szArg, LPCWSTR szTestParamName)
{
    if (wcslen(szArg) == 0)
    {
        return false;
    }

    if (szArg[0] != W('/') && szArg[0] != W('-'))
    {
        return false;
    }

    return !_wcsicmp(szArg + 1, szTestParamName) || !_wcsicmp(szArg + 1, szTestParamName);
}

//
// Returns true if pwzString ends with the string in pwzCandidate
// Ignores case
//
bool StringEndsWith(LPCWSTR pwzString, LPCWSTR pwzCandidate)
{
    size_t stringLength = wcslen(pwzString);
    size_t candidateLength = wcslen(pwzCandidate);

    if (candidateLength > stringLength || stringLength == 0 || candidateLength == 0)
    {
        return false;
    }

    LPCWSTR pwzStringEnd = pwzString + stringLength - candidateLength;

    return !_wcsicmp(pwzStringEnd, pwzCandidate);
}

#ifdef FEATURE_CORECLR
//
// When using the Phone binding model (TrustedPlatformAssemblies), automatically
// detect which path mscorlib.[ni.]dll lies in.
//
bool ComputeMscorlibPathFromTrustedPlatformAssemblies(SString& pwzMscorlibPath, LPCWSTR pwzTrustedPlatformAssemblies)
{
    LPWSTR wszTrustedPathCopy = new WCHAR[wcslen(pwzTrustedPlatformAssemblies) + 1];
    wcscpy_s(wszTrustedPathCopy, wcslen(pwzTrustedPlatformAssemblies) + 1, pwzTrustedPlatformAssemblies);
    wchar_t *context;
    LPWSTR wszSingleTrustedPath = wcstok_s(wszTrustedPathCopy, PATH_SEPARATOR_STR_W, &context);
    
    while (wszSingleTrustedPath != NULL)
    {
        size_t pathLength = wcslen(wszSingleTrustedPath);
        // Strip off enclosing quotes, if present
        if (wszSingleTrustedPath[0] == W('\"') && wszSingleTrustedPath[pathLength-1] == W('\"'))
        {
            wszSingleTrustedPath[pathLength-1] = '\0';
            wszSingleTrustedPath++;
        }

        if (StringEndsWith(wszSingleTrustedPath, DIRECTORY_SEPARATOR_STR_W W("mscorlib.dll")) ||
            StringEndsWith(wszSingleTrustedPath, DIRECTORY_SEPARATOR_STR_W W("mscorlib.ni.dll")))
        {
            pwzMscorlibPath.Set(wszSingleTrustedPath);
            SString::Iterator pwzSeparator = pwzMscorlibPath.End();
            bool retval = true;
            
            if (!SUCCEEDED(CopySystemDirectory(pwzMscorlibPath, pwzMscorlibPath)))
            {
                retval = false;
            }

            delete [] wszTrustedPathCopy;
            return retval;
        }
        
        wszSingleTrustedPath = wcstok_s(NULL, PATH_SEPARATOR_STR_W, &context);
    }
    delete [] wszTrustedPathCopy;

    return false;
}

// Given a path terminated with "\\" and a search mask, this function will add
// the enumerated files, corresponding to the search mask, from the path into
// the refTPAList.
void PopulateTPAList(SString path, LPCWSTR pwszMask, SString &refTPAList, bool fCompilingMscorlib, bool fCreatePDB)
{
    _ASSERTE(path.GetCount() > 0);
    ClrDirectoryEnumerator folderEnumerator(path.GetUnicode(), pwszMask);
    
    while (folderEnumerator.Next())
    {
        // Got a valid enumeration handle and the data about the first file.
        DWORD dwAttributes = folderEnumerator.GetFileAttributes();
        if ((!(dwAttributes & FILE_ATTRIBUTE_DIRECTORY)) && (!(dwAttributes & FILE_ATTRIBUTE_DEVICE)))
        {
            bool fAddDelimiter = (refTPAList.GetCount() > 0)?true:false;
            bool fAddFileToTPAList = true;
            LPCWSTR pwszFilename = folderEnumerator.GetFileName();
            if (fCompilingMscorlib)
            {
                // When compiling mscorlib.dll, no ".ni.dll" should be on the TPAList.
                if (StringEndsWith((LPWSTR)pwszFilename, W(".ni.dll")))
                {
                    fAddFileToTPAList = false;
                }
            }
            else
            {
                // When creating PDBs, we must ensure that .ni.dlls are in the TPAList
                if (!fCreatePDB)
                {
                    // Only mscorlib.ni.dll should be in the TPAList for the compilation of non-mscorlib assemblies.
                    if (StringEndsWith((LPWSTR)pwszFilename, W(".ni.dll")))
                    {
                        if (!StringEndsWith((LPWSTR)pwszFilename, W("mscorlib.ni.dll")))
                        {
                            fAddFileToTPAList = false;
                        }
                    }
                }
                
                // Ensure that mscorlib.dll is also not on the TPAlist for this case.                
                if (StringEndsWith((LPWSTR)pwszFilename, W("mscorlib.dll")))
                {
                    fAddFileToTPAList = false;
                }
            }
            
            if (fAddFileToTPAList)
            {
                if (fAddDelimiter)
                {
                    // Add the path delimiter if we already have entries in the TPAList
                    refTPAList.Append(PATH_SEPARATOR_CHAR_W);
                }
                // Add the path to the TPAList
                refTPAList.Append(path);
                refTPAList.Append(pwszFilename);
            } 
        }
    }
 }

// Given a semi-colon delimited set of absolute folder paths (pwzPlatformAssembliesPaths), this function
// will enumerate all EXE/DLL modules in those folders and add them to the TPAList buffer (refTPAList).
void ComputeTPAListFromPlatformAssembliesPath(LPCWSTR pwzPlatformAssembliesPaths, SString &refTPAList, bool fCompilingMscorlib, bool fCreatePDB)
{
    // We should have a valid pointer to the paths
    _ASSERTE(pwzPlatformAssembliesPaths != NULL);
    
    SString ssPlatformAssembliesPath(pwzPlatformAssembliesPaths);
    
    // Platform Assemblies Path List is semi-colon delimited
    if(ssPlatformAssembliesPath.GetCount() > 0)
    {
        SString::CIterator start = ssPlatformAssembliesPath.Begin();
        SString::CIterator itr = ssPlatformAssembliesPath.Begin();
        SString::CIterator end = ssPlatformAssembliesPath.End();
        SString qualifiedPath;

        while (itr != end)
        {
            start = itr;
            BOOL found = ssPlatformAssembliesPath.Find(itr, PATH_SEPARATOR_CHAR_W);
            if (!found)
            {
                itr = end;
            }

            SString qualifiedPath(ssPlatformAssembliesPath,start,itr);

            if (found)
            {
                itr++;
            }

            unsigned len = qualifiedPath.GetCount();

            if (len > 0)
            {
                if (qualifiedPath[len-1]!=DIRECTORY_SEPARATOR_CHAR_W)
                {
                    qualifiedPath.Append(DIRECTORY_SEPARATOR_CHAR_W);
                }

                // Enumerate the EXE/DLL modules within this path and add them to the TPAList
                EX_TRY
                {
                    PopulateTPAList(qualifiedPath, W("*.exe"), refTPAList, fCompilingMscorlib, fCreatePDB);
                    PopulateTPAList(qualifiedPath, W("*.dll"), refTPAList, fCompilingMscorlib, fCreatePDB);
                }
                EX_CATCH
                {
                    Outputf(W("Warning: Error enumerating files under %s.\n"), qualifiedPath.GetUnicode());
                }
                EX_END_CATCH(SwallowAllExceptions);
            }
        }
    }
}
#endif // FEATURE_CORECLR

extern HMODULE g_hThisInst;

int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv)
{
#ifndef FEATURE_PAL
    g_hThisInst = WszGetModuleHandle(NULL);
#endif

    /////////////////////////////////////////////////////////////////////////
    //
    // Parse the arguments
    //
    bool fDisplayLogo = true;
    DWORD dwFlags = 0;
    LPCWSTR pwzFilename = NULL;
    LPCWSTR pwzPlatformResourceRoots = nullptr;
    LPCWSTR pwzTrustedPlatformAssemblies = nullptr;
    LPCWSTR pwzAppPaths = nullptr;
    LPCWSTR pwzAppNiPaths = nullptr;
    LPCWSTR pwzPlatformAssembliesPaths = nullptr;
    LPCWSTR pwzPlatformWinmdPaths = nullptr;
    StackSString wzDirectoryToStorePDB;
    bool fCreatePDB = false;
    bool fGeneratePDBLinesInfo = false;
    LPWSTR pwzSearchPathForManagedPDB = NULL;
    LPCWSTR pwzOutputFilename = NULL;
    LPCWSTR pwzPublicKeys = nullptr;

    HRESULT hr;

#ifndef PLATFORM_UNIX
    // This is required to properly display Unicode characters
    _setmode(_fileno(stdout), _O_U8TEXT);
#endif

    // Skip this executable path
    argv++;
    argc--;

    ConsoleArgs consoleArgs;
    int argc2;
    LPWSTR *argv2;

    if (argc == 0)
    {
        PrintUsageHelper();
        exit(INVALID_ARGUMENTS);
    }
    
    if (!consoleArgs.ExpandResponseFiles(argc, argv, &argc2, &argv2))
    {
        if (consoleArgs.ErrorMessage() != nullptr)
        {
            wprintf(consoleArgs.ErrorMessage());
            exit(FAILURE_RESULT);
        }
    }
    
    argc = argc2;
    argv = argv2;

    // By default, Crossgen will assume code-generation for fulltrust domains unless /PartialTrust switch is specified
    dwFlags |= NGENWORKER_FLAGS_FULLTRUSTDOMAIN;

#ifdef FEATURE_CORECLR
    // By default, Crossgen will generate readytorun images unless /FragileNonVersionable switch is specified
    dwFlags |= NGENWORKER_FLAGS_READYTORUN;
#endif

    while (argc > 0)
    {
        if (MatchParameter(*argv, W("?"))
            || MatchParameter(*argv, W("help")))
        {
            PrintUsageHelper();
            exit(INVALID_ARGUMENTS);
        }
        else if (MatchParameter(*argv, W("nologo")))
        {
            fDisplayLogo = false;
        }
        else if (MatchParameter(*argv, W("Tuning")))
        {
            dwFlags |= NGENWORKER_FLAGS_TUNING;
        }
        else if (MatchParameter(*argv, W("MissingDependenciesOK")))
        {
            dwFlags |= NGENWORKER_FLAGS_MISSINGDEPENDENCIESOK;
        }
#ifdef FEATURE_CORECLR
        else if (MatchParameter(*argv, W("PartialTrust")))
        {
            // Clear the /fulltrust flag
            dwFlags = dwFlags & ~NGENWORKER_FLAGS_FULLTRUSTDOMAIN;
        }
        else if (MatchParameter(*argv, W("FullTrust")))
        {
            // Keep the "/fulltrust" switch around but let it be no-nop. Without this, any usage of /fulltrust will result in crossgen command-line
            // parsing failure. Considering that scripts all over (CLR, Phone Build, etc) specify that switch, we let it be as opposed to going
            // and fixing all the scripts.
            //
            // We dont explicitly set the flag here again so that if "/PartialTrust" is specified, then it will successfully override the default
            // fulltrust behaviour.
        }
#endif
#ifdef FEATURE_LEGACYNETCF
        else if (MatchParameter(*argv, W("PreWP8App")))
        {
            dwFlags |= NGENWORKER_FLAGS_APPCOMPATWP8;
        }
#endif
#ifdef FEATURE_WINMD_RESILIENT
        else if (MatchParameter(*argv, W("WinMDResilient")))
        {
            dwFlags |= NGENWORKER_FLAGS_WINMD_RESILIENT;
        }
#endif
#ifdef FEATURE_READYTORUN_COMPILER
        else if (MatchParameter(*argv, W("ReadyToRun")))
        {
            dwFlags |= NGENWORKER_FLAGS_READYTORUN;
        }
        else if (MatchParameter(*argv, W("FragileNonVersionable")))
        {
            dwFlags &= ~NGENWORKER_FLAGS_READYTORUN;
        }
#endif
#ifdef FEATURE_CORECLR
        else if (MatchParameter(*argv, W("NoMetaData")))
        {
            dwFlags |= NGENWORKER_FLAGS_NO_METADATA;
        }
#endif
        else if (MatchParameter(*argv, W("out")))
        {
            if (pwzOutputFilename != NULL)
            {
                Output(W("Cannot specify multiple output files.\n"));
                exit(INVALID_ARGUMENTS);
            }
            pwzOutputFilename = argv[1];
            argv++;
            argc--;
        }
        else if (MatchParameter(*argv, W("in")))
        {
            if (pwzFilename != NULL)
            {
                Output(W("Cannot specify multiple input files.\n"));
                exit(INVALID_ARGUMENTS);
            }
            pwzFilename = argv[1];
            argv++;
            argc--;
        }
#ifdef FEATURE_CORECLR
        else if (MatchParameter(*argv, W("Trusted_Platform_Assemblies")) && (argc > 1))
        {
            pwzTrustedPlatformAssemblies = argv[1];

            // skip path list
            argv++;
            argc--;
        }
        else if (MatchParameter(*argv, W("Platform_Resource_Roots")) && (argc > 1))
        {
            pwzPlatformResourceRoots = argv[1];

            // skip path list
            argv++;
            argc--;
        }
        else if (MatchParameter(*argv, W("App_Paths")) && (argc > 1))
        {
            pwzAppPaths = argv[1];

            // skip User app path
            argv++;
            argc--;
        }
#ifndef NO_NGENPDB
        else if (MatchParameter(*argv, W("App_Ni_Paths")) && (argc > 1))
        {
            pwzAppNiPaths = argv[1];

            // skip User app path
            argv++;
            argc--;
        }
#endif // NO_NGENPDB
#endif // FEATURE_CORECLR
        else if (MatchParameter(*argv, W("Platform_Assemblies_Paths")) && (argc > 1))
        {
            pwzPlatformAssembliesPaths = argv[1];
            
            // skip path list
            argv++;
            argc--;
        }
#ifdef FEATURE_COMINTEROP
        else if (MatchParameter(*argv, W("Platform_Winmd_Paths")) && (argc > 1))
        {
            pwzPlatformWinmdPaths = argv[1];

            // skip User app path
            argv++;
            argc--;
        }
#endif // FEATURE_COMINTEROP
#ifndef NO_NGENPDB
        else if (MatchParameter(*argv, W("CreatePDB")) && (argc > 1))
        {
            // syntax: /CreatePDB <directory to store PDB> [/lines  [<search path for managed PDB>] ]
            
            // Parse: /CreatePDB
            fCreatePDB = true;
            argv++;
            argc--;

            // Clear the /fulltrust flag - /CreatePDB does not work with any other flags.
            dwFlags = dwFlags & ~(NGENWORKER_FLAGS_FULLTRUSTDOMAIN | NGENWORKER_FLAGS_READYTORUN);

            // Parse: <directory to store PDB>
            wzDirectoryToStorePDB.Set(argv[0]);
            argv++;
            argc--;

            // Ensure output dir ends in a backslash, or else diasymreader has issues
            if (wzDirectoryToStorePDB[wzDirectoryToStorePDB.GetCount()-1] != DIRECTORY_SEPARATOR_CHAR_W)
            {
                wzDirectoryToStorePDB.Append(DIRECTORY_SEPARATOR_STR_W);
            }

            if (argc == 0)
            {
                Output(W("The /CreatePDB switch requires <directory to store PDB> and <assembly name>.\n"));
                exit(FAILURE_RESULT);
            }

            // [/lines  [<search path for managed PDB>] ]
            if (MatchParameter(*argv, W("lines")) && (argc > 1))
            {
                // Parse: /lines
                fGeneratePDBLinesInfo = true;
                argv++;
                argc--;

                if (argc == 0)
                {
                    Output(W("The /CreatePDB switch requires <directory to store PDB> and <assembly name>.\n"));
                    exit(FAILURE_RESULT);
                }

                if (argc > 1)
                {
                    // Parse: <search path for managed PDB>
                    pwzSearchPathForManagedPDB = argv[0];
                    argv++;
                    argc--;
                }
            }

            // Undo last arg iteration, since we do it for all cases at the bottom of
            // the loop
            argv--;
            argc++;
        }
#endif // NO_NGENPDB
#ifdef FEATURE_PERFMAP
        else if (MatchParameter(*argv, W("CreatePerfMap")) && (argc > 1))
        {
            // syntax: /CreatePerfMap <directory to store perfmap>

            // Parse: /CreatePerfMap
            // NOTE: We use the same underlying PDB logic.
            fCreatePDB = true;
            argv++;
            argc--;

            // Clear the /fulltrust flag - /CreatePerfMap does not work with any other flags.
            dwFlags = dwFlags & ~NGENWORKER_FLAGS_FULLTRUSTDOMAIN;

            // Clear the /ready to run flag - /CreatePerfmap does not work with any other flags.
            dwFlags = dwFlags & ~NGENWORKER_FLAGS_READYTORUN;

            // Parse: <directory to store PDB>
            wzDirectoryToStorePDB.Set(argv[0]);
            argv++;
            argc--;

            // Ensure output dir ends in a backslash
            if (wzDirectoryToStorePDB[wcslen(wzDirectoryToStorePDB)-1] != DIRECTORY_SEPARATOR_CHAR_W)
            {
                wzDirectoryToStorePDB.Append(DIRECTORY_SEPARATOR_STR_W);
            }

            if (argc == 0)
            {
                Output(W("The /CreatePerfMap switch requires <directory to store perfmap> and <assembly name>.\n"));
                exit(FAILURE_RESULT);
            }

            // Undo last arg iteration, since we do it for all cases at the bottom of
            // the loop
            argv--;
            argc++;
        }
#endif // FEATURE_PERFMAP
        else
        {
            if (argc == 1)
            {
#if !defined(FEATURE_PAL)
                // When not running on Mac, which can have forward-slash pathnames, we know
                // a command switch here means an invalid argument.
                if (*argv[0] == W('-') || *argv[0] == W('/'))
                {
                    Outputf(W("Invalid parameter: %s\n"), *argv);
                    exit(INVALID_ARGUMENTS);
                }
#endif //!FEATURE_PAL
                // The last thing on the command line is an assembly name or path, and
                // because we got this far is not an argument like /nologo. Because this
                // code works on Mac, with forward-slash pathnames, we can't assume
                // anything with a forward slash is an argument. So we just always
                // assume the last thing on the command line must be an assembly name.

                if (pwzFilename != NULL)
                {
                    Output(W("Cannot use /In and specify an input file as the last argument.\n"));
                    exit(INVALID_ARGUMENTS);
                }
                
                pwzFilename = *argv;
                break;
            }
            else
            {
                Outputf(W("Invalid parameter: %s\n"), *argv);
                exit(INVALID_ARGUMENTS);
            }
        }

        argv++;
        argc--;
    }

    if (pwzFilename == NULL)
    {
        Output(W("You must specify an assembly to compile\n"));
        exit(INVALID_ARGUMENTS);
    }

    if (fCreatePDB && (dwFlags != 0))
    {
        Output(W("The /CreatePDB switch cannot be used with other switches, except /lines and the various path switches.\n"));
        exit(FAILURE_RESULT);
    }

    if (pwzAppNiPaths != nullptr && !fCreatePDB)
    {
        Output(W("The /App_Ni_Paths switch can only be used with the /CreatePDB switch.\n"));
        exit(FAILURE_RESULT);
    }

#if defined(FEATURE_CORECLR)
    if ((pwzTrustedPlatformAssemblies != nullptr) && (pwzPlatformAssembliesPaths != nullptr))
    {
        Output(W("The /Trusted_Platform_Assemblies and /Platform_Assemblies_Paths switches cannot be both specified.\n"));
        exit(FAILURE_RESULT);
    }

    if ((dwFlags & NGENWORKER_FLAGS_NO_METADATA) != 0)
    {
        const size_t windowsDotWinmdLength = 13;    // Length of string "Windows.winmd"
        size_t filenameLength = wcslen(pwzFilename);
        bool isWindowsDotWinmd = true;
        if (filenameLength < windowsDotWinmdLength ||
            _wcsicmp(pwzFilename + filenameLength - windowsDotWinmdLength, W("windows.winmd")) != 0)
        {
            isWindowsDotWinmd = false;
        }
        else if (filenameLength > windowsDotWinmdLength)
        {
            WCHAR pathSeparator = pwzFilename[filenameLength - windowsDotWinmdLength - 1];
            if (pathSeparator != W('\\') && pathSeparator != W('/') && pathSeparator != W(':'))
            {
                isWindowsDotWinmd = false;
            }
        }
        if (!isWindowsDotWinmd)
        {
            Output(W("The /NoMetaData switch can only be used with Windows.winmd.\n"));
            exit(FAILURE_RESULT);
        }
    }
#endif // FEATURE_CORESYSTEM

#ifdef FEATURE_READYTORUN_COMPILER
    if (((dwFlags & NGENWORKER_FLAGS_TUNING) != 0) && ((dwFlags & NGENWORKER_FLAGS_READYTORUN) != 0))
    {
        Output(W("The /Tuning switch cannot be used with /ReadyToRun switch.\n"));
        exit(FAILURE_RESULT);
    }
#endif
    
    // All argument processing has happened by now. The only messages that should appear before here are errors
    // related to argument parsing, such as the Usage message. Afterwards, other messages can appear.

    /////////////////////////////////////////////////////////////////////////
    //
    // Start processing
    //

    if (fDisplayLogo)
    {
        PrintLogoHelper();
    }

    PathString wzTrustedPathRoot;

#ifdef FEATURE_CORECLR
    SString ssTPAList;  

    if (fCreatePDB)
    {
        // While creating PDB, assembly binder gives preference to files in TPA.
        // This can create difficulties if the input file is not in TPA.
        // To avoid this issue, put the input file as the first item in TPA.
        ssTPAList.Append(pwzFilename);
    }
    
    // Are we compiling mscorlib.dll? 
    bool fCompilingMscorlib = StringEndsWith((LPWSTR)pwzFilename, W("mscorlib.dll"));

    if (fCompilingMscorlib)
        dwFlags &= ~NGENWORKER_FLAGS_READYTORUN;

    if(pwzPlatformAssembliesPaths != nullptr)
    {
        // Platform_Assemblies_Paths command line switch has been specified.
        _ASSERTE(pwzTrustedPlatformAssemblies == nullptr);
        
        // Formulate the TPAList from Platform_Assemblies_Paths
        ComputeTPAListFromPlatformAssembliesPath(pwzPlatformAssembliesPaths, ssTPAList, fCompilingMscorlib, fCreatePDB);
        pwzTrustedPlatformAssemblies = (WCHAR *)ssTPAList.GetUnicode();
        pwzPlatformAssembliesPaths = NULL;
    }

    if (pwzTrustedPlatformAssemblies != nullptr)
    {
        if (ComputeMscorlibPathFromTrustedPlatformAssemblies(wzTrustedPathRoot, pwzTrustedPlatformAssemblies))
        {
            pwzPlatformAssembliesPaths = wzTrustedPathRoot.GetUnicode();
            SetMscorlibPath(pwzPlatformAssembliesPaths);
        }
    }
#endif // FEATURE_CORECLR

    if (pwzPlatformAssembliesPaths == NULL)
    {
        if (!WszGetModuleFileName(NULL, wzTrustedPathRoot))
        {
            ERROR_WIN32(W("Error: GetModuleFileName failed (%d)\n"), GetLastError());
            exit(CLR_INIT_ERROR);
        }
        
        if (SUCCEEDED(CopySystemDirectory(wzTrustedPathRoot, wzTrustedPathRoot)))
        {
            pwzPlatformAssembliesPaths = wzTrustedPathRoot.GetUnicode();
        }
        else
        {
            ERROR_HR(W("Error: wcsrchr returned NULL; GetModuleFileName must have given us something bad\n"), E_UNEXPECTED);
            exit(CLR_INIT_ERROR);
        }
        
        
    }

    // Initialize the logger
    SetSvcLogger(&g_CrossgenLogger);

    //Step - Compile the assembly

    if (fCreatePDB)
    {
        hr = CreatePDBWorker(
            pwzFilename, 
            pwzPlatformAssembliesPaths, 
            pwzTrustedPlatformAssemblies, 
            pwzPlatformResourceRoots, 
            pwzAppPaths, 
            pwzAppNiPaths,
            wzDirectoryToStorePDB, 
            fGeneratePDBLinesInfo, 
            pwzSearchPathForManagedPDB,
            pwzPlatformWinmdPaths);
        
    }
    else
    {
        hr = NGenWorker(pwzFilename, dwFlags,
         pwzPlatformAssembliesPaths,
         pwzTrustedPlatformAssemblies,
         pwzPlatformResourceRoots,
         pwzAppPaths,
         pwzOutputFilename,
         pwzPlatformWinmdPaths
         );
    }
    

    if (FAILED(hr))
    {
        if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
        {
            OutputErrf(W("Error: file \"%s\" or one of its dependencies was not found\n"), pwzFilename);
            exit(ASSEMBLY_NOT_FOUND);
        }
        else
        {
            OutputErrf(W("Error: compilation failed for \"%s\" (0x%08x)\n"), pwzFilename, hr);
            exit(hr);
        }
    }

    return 0;
}

#ifdef PLATFORM_UNIX
int main(int argc, char *argv[])
{
    if (0 != PAL_Initialize(argc, argv))
    {
        return FAILURE_RESULT;
    }

    wchar_t **wargv = new wchar_t*[argc];
    for (int i = 0; i < argc; i++)
    {
        size_t len = strlen(argv[i]) + 1;
        wargv[i] = new wchar_t[len];
        WszMultiByteToWideChar(CP_ACP, 0, argv[i], -1, wargv[i], len);
    }

    int ret = wmain(argc, wargv);

    for (int i = 0; i < argc; i++)
    {
        delete[] wargv[i];
    }
    delete[] wargv;

    return ret;
}
#endif // PLATFORM_UNIX