summaryrefslogtreecommitdiff
path: root/Tools/CCode/Source/GenTEImage/GenTEImage.c
blob: 665498ac2c8099f9abc7f8128cce7d5c3c2d1533 (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
/*++

Copyright (c)  1999-2006 Intel Corporation. All rights reserved
This program and the accompanying materials are licensed and made available 
under the terms and conditions of the BSD License which accompanies this 
distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

Module Name:

  GenTEImage.c
  
Abstract:

  Utility program to shrink a PE32 image down by replacing
  the DOS, PE, and optional headers with a minimal header.

--*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <Common/UefiBaseTypes.h>
#include <Common/EfiImage.h> // for PE32 structure definitions

#include "CommonLib.h"
#include "EfiUtilityMsgs.h"

//
// Version of this utility
//
#define UTILITY_NAME    "GenTEImage"
#define UTILITY_MAJOR_VERSION   0
#define UTILITY_MINOR_VERSION   11

//
// Define the max length of a filename
//
#define MAX_PATH                  256
#define DEFAULT_OUTPUT_EXTENSION  ".te"

//
// Use this to track our command-line options and globals
//
struct {
  INT8  OutFileName[MAX_PATH];
  INT8  InFileName[MAX_PATH];
  INT8  Verbose;
  INT8  Dump;
} mOptions;

//
// Use these to convert from machine type value to a named type
//
typedef struct {
  UINT16  Value;
  INT8    *Name;
} STRING_LOOKUP;

static STRING_LOOKUP  mMachineTypes[] = {
  EFI_IMAGE_MACHINE_IA32,
  "IA32",
  EFI_IMAGE_MACHINE_IA64,
  "IA64",
  EFI_IMAGE_MACHINE_EBC,
  "EBC",
  0,
  NULL
};

static STRING_LOOKUP  mSubsystemTypes[] = {
  EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION,
  "EFI application",
  EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER,
  "EFI boot service driver",
  EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER,
  "EFI runtime driver",
  0,
  NULL
};
//
//  Function prototypes
//
static
void
Version (
  VOID
  );

static
void
Usage (
  VOID
  );

static
STATUS
ParseCommandLine (
  int       Argc,
  char      *Argv[]
  );

static
STATUS
CheckPE32File (
  INT8      *FileName,
  FILE      *Fptr,
  UINT16    *MachineType,
  UINT16    *SubSystem
  );

static
STATUS
ProcessFile (
  INT8      *InFileName,
  INT8      *OutFileName
  );

static
void
DumpImage (
  INT8      *FileName
  );

static
INT8                  *
GetMachineTypeStr (
  UINT16    MachineType
  );

static
INT8                  *
GetSubsystemTypeStr (
  UINT16  SubsystemType
  );

main (
  int   Argc,
  char  *Argv[]
  )
/*++

Routine Description:
  

Arguments:

  Argc            - standard C main() argument count

  Argv            - standard C main() argument list

Returns:

  0             success
  non-zero      otherwise

--*/
// GC_TODO:    ] - add argument and description to function comment
{
  INT8    *Ext;
  UINT32  Status;

  SetUtilityName (UTILITY_NAME);
  //
  // Parse the command line arguments
  //
  if (ParseCommandLine (Argc, Argv)) {
    return STATUS_ERROR;
  }
  //
  // If dumping an image, then do that and quit
  //
  if (mOptions.Dump) {
    DumpImage (mOptions.InFileName);
    goto Finish;
  }
  //
  // Determine the output filename. Either what they specified on
  // the command line, or the first input filename with a different extension.
  //
  if (!mOptions.OutFileName[0]) {
    strcpy (mOptions.OutFileName, mOptions.InFileName);
    //
    // Find the last . on the line and replace the filename extension with
    // the default
    //
    for (Ext = mOptions.OutFileName + strlen (mOptions.OutFileName) - 1;
         (Ext >= mOptions.OutFileName) && (*Ext != '.') && (*Ext != '\\');
         Ext--
        )
      ;
    //
    // If dot here, then insert extension here, otherwise append
    //
    if (*Ext != '.') {
      Ext = mOptions.OutFileName + strlen (mOptions.OutFileName);
    }

    strcpy (Ext, DEFAULT_OUTPUT_EXTENSION);
  }
  //
  // Make sure we don't have the same filename for input and output files
  //
  if (stricmp (mOptions.OutFileName, mOptions.InFileName) == 0) {
    Error (NULL, 0, 0, mOptions.OutFileName, "input and output file names must be different");
    goto Finish;
  }
  //
  // Process the file
  //
  ProcessFile (mOptions.InFileName, mOptions.OutFileName);
Finish:
  Status = GetUtilityStatus ();
  return Status;
}

static
STATUS
ProcessFile (
  INT8      *InFileName,
  INT8      *OutFileName
  )
/*++

Routine Description:
  
  Process a PE32 EFI file.

Arguments:
  
  InFileName      - the file name pointer to the input file
  OutFileName     - the file name pointer to the output file

Returns:

  STATUS_SUCCESS  - the process has been finished successfully
  STATUS_ERROR    - error occured during the processing

--*/
{
  STATUS                      Status;
  FILE                        *InFptr;
  FILE                        *OutFptr;
  UINT16                      MachineType;
  UINT16                      SubSystem;
  EFI_TE_IMAGE_HEADER         TEImageHeader;
  UINT32                      PESigOffset;
  EFI_IMAGE_FILE_HEADER       FileHeader;
  EFI_IMAGE_OPTIONAL_HEADER32 OptionalHeader32;
  EFI_IMAGE_OPTIONAL_HEADER64 OptionalHeader64;
  UINT32                      BytesStripped;
  UINT32                      FileSize;
  UINT8                       *Buffer;
  long                        SaveFilePosition;

  InFptr  = NULL;
  OutFptr = NULL;
  Buffer  = NULL;
  Status  = STATUS_ERROR;

  //
  // Try to open the input file
  //
  if ((InFptr = fopen (InFileName, "rb")) == NULL) {
    Error (NULL, 0, 0, InFileName, "failed to open input file for reading");
    return STATUS_ERROR;
  }
  //
  // Double-check the file to make sure it's what we expect it to be
  //

  if (CheckPE32File (InFileName, InFptr, &MachineType, &SubSystem) != STATUS_SUCCESS) {
    goto Finish;
  }
  //
  // Initialize our new header
  //
  memset (&TEImageHeader, 0, sizeof (EFI_TE_IMAGE_HEADER));

  //
  // Seek to the end to get the file size
  //
  fseek (InFptr, 0, SEEK_END);
  FileSize = ftell (InFptr);
  fseek (InFptr, 0, SEEK_SET);

  //
  // Per the PE/COFF specification, at offset 0x3C in the file is a 32-bit
  // offset (from the start of the file) to the PE signature, which always
  // follows the MSDOS stub. The PE signature is immediately followed by the
  // COFF file header.
  //
  //
  if (fseek (InFptr, 0x3C, SEEK_SET) != 0) {
    Error (NULL, 0, 0, InFileName, "failed to seek to PE signature in file", NULL);
    goto Finish;
  }

  if (fread (&PESigOffset, sizeof (PESigOffset), 1, InFptr) != 1) {
    Error (NULL, 0, 0, InFileName, "failed to read PE signature offset from file");
    goto Finish;
  }

  if (fseek (InFptr, PESigOffset + 4, SEEK_SET) != 0) {
    Error (NULL, 0, 0, InFileName, "failed to seek to PE signature");
    goto Finish;
  }
  //
  // We should now be at the COFF file header. Read it in and verify it's
  // of an image type we support.
  //
  if (fread (&FileHeader, sizeof (EFI_IMAGE_FILE_HEADER), 1, InFptr) != 1) {
    Error (NULL, 0, 0, InFileName, "failed to read file header from image");
    goto Finish;
  }

  if ((FileHeader.Machine != EFI_IMAGE_MACHINE_IA32) && (FileHeader.Machine != EFI_IMAGE_MACHINE_IA64)) {
    Error (NULL, 0, 0, InFileName, "image is of an unsupported machine type 0x%X", (UINT32) FileHeader.Machine);
    goto Finish;
  }
  //
  // Calculate the total number of bytes we're going to strip off. The '4' is for the
  // PE signature PE\0\0. Then sanity check the size.
  //
  BytesStripped = PESigOffset + 4 + sizeof (EFI_IMAGE_FILE_HEADER) + FileHeader.SizeOfOptionalHeader;
  if (BytesStripped >= FileSize) {
    Error (NULL, 0, 0, InFileName, "attempt to strip more bytes than the total file size");
    goto Finish;
  }

  if (BytesStripped &~0xFFFF) {
    Error (NULL, 0, 0, InFileName, "attempt to strip more than 64K bytes", NULL);
    goto Finish;
  }

  TEImageHeader.StrippedSize = (UINT16) BytesStripped;

  //
  // Read in the optional header. Assume PE32, and if not, then re-read as PE32+
  //
  SaveFilePosition = ftell (InFptr);
  if (fread (&OptionalHeader32, sizeof (EFI_IMAGE_OPTIONAL_HEADER32), 1, InFptr) != 1) {
    Error (NULL, 0, 0, InFileName, "failed to read optional header from input file");
    goto Finish;
  }

  if (OptionalHeader32.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
    //
    // Fill in our new header with required data directory entries
    //
    TEImageHeader.AddressOfEntryPoint = OptionalHeader32.AddressOfEntryPoint;
    //
    // - BytesStripped + sizeof (EFI_TE_IMAGE_HEADER);
    //
    // We're going to pack the subsystem into 1 byte. Make sure it fits
    //
    if (OptionalHeader32.Subsystem &~0xFF) {
      Error (
        NULL,
        0,
        0,
        InFileName,
        NULL,
        "image subsystem 0x%X cannot be packed into 1 byte",
        (UINT32) OptionalHeader32.Subsystem
        );
      goto Finish;
    }

    TEImageHeader.Subsystem   = (UINT8) OptionalHeader32.Subsystem;
    TEImageHeader.BaseOfCode  = OptionalHeader32.BaseOfCode;
    TEImageHeader.ImageBase   = (UINT64) (OptionalHeader32.ImageBase);
    if (OptionalHeader32.NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = OptionalHeader32.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = OptionalHeader32.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
    }

    if (OptionalHeader32.NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = OptionalHeader32.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = OptionalHeader32.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
    }
  } else if (OptionalHeader32.Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
    //
    // Rewind and re-read the optional header
    //
    fseek (InFptr, SaveFilePosition, SEEK_SET);
    if (fread (&OptionalHeader64, sizeof (EFI_IMAGE_OPTIONAL_HEADER64), 1, InFptr) != 1) {
      Error (NULL, 0, 0, InFileName, "failed to re-read optional header from input file");
      goto Finish;
    }

    TEImageHeader.AddressOfEntryPoint = OptionalHeader64.AddressOfEntryPoint;
    //
    // - BytesStripped + sizeof (EFI_TE_IMAGE_HEADER);
    //
    // We're going to pack the subsystem into 1 byte. Make sure it fits
    //
    if (OptionalHeader64.Subsystem &~0xFF) {
      Error (
        NULL,
        0,
        0,
        InFileName,
        NULL,
        "image subsystem 0x%X cannot be packed into 1 byte",
        (UINT32) OptionalHeader64.Subsystem
        );
      goto Finish;
    }

    TEImageHeader.Subsystem   = (UINT8) OptionalHeader64.Subsystem;
    TEImageHeader.BaseOfCode  = OptionalHeader32.BaseOfCode;
    TEImageHeader.ImageBase = (UINT64) (OptionalHeader64.ImageBase);
    if (OptionalHeader64.NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC) {
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = OptionalHeader64.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = OptionalHeader64.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
    }

    if (OptionalHeader64.NumberOfRvaAndSizes > EFI_IMAGE_DIRECTORY_ENTRY_DEBUG) {
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = OptionalHeader64.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
      TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = OptionalHeader64.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
    }
  } else {
    Error (
      NULL,
      0,
      0,
      InFileName,
      "unsupported magic number 0x%X found in optional header",
      (UINT32) OptionalHeader32.Magic
      );
    goto Finish;
  }
  //
  // Fill in the remainder of our new image header
  //
  TEImageHeader.Signature = EFI_TE_IMAGE_HEADER_SIGNATURE;
  TEImageHeader.Machine   = FileHeader.Machine;
  //
  // We're going to pack the number of sections into a single byte. Make sure it fits.
  //
  if (FileHeader.NumberOfSections &~0xFF) {
    Error (
      NULL,
      0,
      0,
      InFileName,
      NULL,
      "image's number of sections 0x%X cannot be packed into 1 byte",
      (UINT32) FileHeader.NumberOfSections
      );
    goto Finish;
  }

  TEImageHeader.NumberOfSections = (UINT8) FileHeader.NumberOfSections;

  //
  // Now open our output file
  //
  if ((OutFptr = fopen (OutFileName, "wb")) == NULL) {
    Error (NULL, 0, 0, OutFileName, "failed to open output file for writing");
    goto Finish;
  }
  //
  // Write the TE header
  //
  if (fwrite (&TEImageHeader, sizeof (EFI_TE_IMAGE_HEADER), 1, OutFptr) != 1) {
    Error (NULL, 0, 0, "failed to write image header to output file", NULL);
    goto Finish;
  }
  //
  // Position into the input file, read the part we're not stripping, and
  // write it out.
  //
  fseek (InFptr, BytesStripped, SEEK_SET);
  Buffer = (UINT8 *) malloc (FileSize - BytesStripped);
  if (Buffer == NULL) {
    Error (NULL, 0, 0, "application error", "failed to allocate memory");
    goto Finish;
  }

  if (fread (Buffer, FileSize - BytesStripped, 1, InFptr) != 1) {
    Error (NULL, 0, 0, InFileName, "failed to read remaining contents of input file");
    goto Finish;
  }

  if (fwrite (Buffer, FileSize - BytesStripped, 1, OutFptr) != 1) {
    Error (NULL, 0, 0, OutFileName, "failed to write all bytes to output file");
    goto Finish;
  }

  Status = STATUS_SUCCESS;

Finish:
  if (InFptr != NULL) {
    fclose (InFptr);
  }
  //
  // Close the output file. If there was an error, delete the output file so
  // that a subsequent build will rebuild it.
  //
  if (OutFptr != NULL) {
    fclose (OutFptr);
    if (GetUtilityStatus () == STATUS_ERROR) {
      remove (OutFileName);
    }
  }

  //
  // Free up our buffer
  //
  if (Buffer != NULL) {
    free (Buffer);
  }

  return Status;
}

static
STATUS
CheckPE32File (
  INT8      *FileName,
  FILE      *Fptr,
  UINT16    *MachineType,
  UINT16    *SubSystem
  )
/*++

Routine Description:

  GC_TODO: Add function description

Arguments:

  FileName    - GC_TODO: add argument description
  Fptr        - GC_TODO: add argument description
  MachineType - GC_TODO: add argument description
  SubSystem   - GC_TODO: add argument description

Returns:

  GC_TODO: add return values

--*/
{
  /*++

Routine Description:
  
  Given a file pointer to a supposed PE32 image file, verify that it is indeed a
  PE32 image file, and then return the machine type in the supplied pointer.

Arguments:

  Fptr          File pointer to the already-opened PE32 file
  MachineType   Location to stuff the machine type of the PE32 file. This is needed
                because the image may be Itanium-based, IA32, or EBC.

Returns:

  0             success
  non-zero      otherwise

--*/
  EFI_IMAGE_DOS_HEADER      DosHeader;
  EFI_IMAGE_FILE_HEADER     FileHdr;
  EFI_IMAGE_OPTIONAL_HEADER OptionalHdr;
  UINT32                    PESig;
  STATUS                    Status;

  Status = STATUS_ERROR;
  //
  // Position to the start of the file
  //
  fseek (Fptr, 0, SEEK_SET);
  //
  // Read the DOS header
  //
  if (fread (&DosHeader, sizeof (DosHeader), 1, Fptr) != 1) {
    Error (NULL, 0, 0, FileName, "failed to read the DOS stub from the input file");
    goto Finish;
  }
  //
  // Check the magic number (0x5A4D)
  //
  if (DosHeader.e_magic != EFI_IMAGE_DOS_SIGNATURE) {
    Error (NULL, 0, 0, FileName, "input file does not appear to be a PE32 image (magic number)");
    goto Finish;
  }
  //
  // Position into the file and check the PE signature
  //
  fseek (Fptr, (long) DosHeader.e_lfanew, SEEK_SET);
  if (fread (&PESig, sizeof (PESig), 1, Fptr) != 1) {
    Error (NULL, 0, 0, FileName, "failed to read PE signature bytes");
    goto Finish;
  }
  //
  // Check the PE signature in the header "PE\0\0"
  //
  if (PESig != EFI_IMAGE_NT_SIGNATURE) {
    Error (NULL, 0, 0, FileName, "file does not appear to be a PE32 image (signature)");
    goto Finish;
  }
  //
  // Read the file header
  //
  if (fread (&FileHdr, sizeof (FileHdr), 1, Fptr) != 1) {
    Error (NULL, 0, 0, FileName, "failed to read PE file header from input file");
    goto Finish;
  }
  //
  // Read the optional header so we can get the subsystem
  //
  if (fread (&OptionalHdr, sizeof (OptionalHdr), 1, Fptr) != 1) {
    Error (NULL, 0, 0, FileName, "failed to read COFF optional header from input file");
    goto Finish;
  }

  //
  // Check FileAlginment and SectionAlignment match or not
  // Because TeImage header doesn't record filealginment and sectionalignment info, 
  // TeImage is used for PEIM and PeiCore XIP module. 
  // So, check alignment match before generate TeImage to check.
  //
  if (OptionalHdr.SectionAlignment != OptionalHdr.FileAlignment) {
    Error (NULL, 0, 0, FileName, "Section-Alignment and File-Alignment does not match");
    goto Finish;
  }

  *SubSystem = OptionalHdr.Subsystem;
  if (mOptions.Verbose) {
    fprintf (stdout, "  Got subsystem = 0x%X from image\n", (int) *SubSystem);
  }
  //
  // Good to go
  //
  Status = STATUS_SUCCESS;
Finish:
  fseek (Fptr, 0, SEEK_SET);
  return Status;
}

static
int
ParseCommandLine (
  int         Argc,
  char        *Argv[]
  )
/*++

Routine Description:
  
  Given the Argc/Argv program arguments, and a pointer to an options structure,
  parse the command-line options and check their validity.


Arguments:

  Argc            - standard C main() argument count
  Argv            - standard C main() argument list

Returns:

  STATUS_SUCCESS    success
  non-zero          otherwise

--*/
// GC_TODO:    ] - add argument and description to function comment
{
  //
  // Clear out the options
  //
  memset ((char *) &mOptions, 0, sizeof (mOptions));
  //
  // Skip over the program name
  //
  Argc--;
  Argv++;
  //
  // If no arguments, assume they want usage info
  //
  if (Argc == 0) {
    Usage ();
    return STATUS_ERROR;
  }
  
  if ((strcmp(Argv[0], "-h") == 0) || (strcmp(Argv[0], "--help") == 0) ||
      (strcmp(Argv[0], "-?") == 0) || (strcmp(Argv[0], "/?") == 0)) {
    Usage();
    return STATUS_ERROR;
  }
  
  if ((strcmp(Argv[0], "-V") == 0) || (strcmp(Argv[0], "--version") == 0)) {
    Version();
    return STATUS_ERROR;
  }
  
  //
  // Process until no more arguments
  //
  while ((Argc > 0) && (Argv[0][0] == '-')) {
    if (stricmp (Argv[0], "-o") == 0) {
      //
      // Output filename specified with -o
      // Make sure there's another parameter
      //
      if (Argc > 1) {
        strcpy (mOptions.OutFileName, Argv[1]);
      } else {
        Error (NULL, 0, 0, Argv[0], "missing output file name with option");
        Usage ();
        return STATUS_ERROR;
      }

      Argv++;
      Argc--;
    } else if ((stricmp (Argv[0], "-h") == 0) || (strcmp (Argv[0], "-?") == 0)) {
      //
      // Help option
      //
      Usage ();
      return STATUS_ERROR;
    } else if (stricmp (Argv[0], "-v") == 0) {
      //
      // -v for verbose
      //
      mOptions.Verbose = 1;
    } else if (stricmp (Argv[0], "-dump") == 0) {
      //
      // -dump for dumping an image
      //
      mOptions.Dump = 1;
    } else {
      Error (NULL, 0, 0, Argv[0], "unrecognized option");
      Usage ();
      return STATUS_ERROR;
    }
    //
    // Next argument
    //
    Argv++;
    Argc--;
  }
  //
  // Better be one more arg for input file name
  //
  if (Argc == 0) {
    Error (NULL, 0, 0, "input file name required", NULL);
    Usage ();
    return STATUS_ERROR;
  }

  if (Argc != 1) {
    Error (NULL, 0, 0, Argv[1], "extra arguments on command line");
    return STATUS_ERROR;
  }

  strcpy (mOptions.InFileName, Argv[0]);
  return STATUS_SUCCESS;
}

static
void 
Version(
  void
)
/*++

Routine Description:

  Displays the standard utility information to SDTOUT

Arguments:

  None

Returns:

  None

--*/
{
  printf ("%s v%d.%d -Utility to generate a TE image from an EFI PE32 image.\n", UTILITY_NAME, UTILITY_MAJOR_VERSION, UTILITY_MINOR_VERSION);
  printf ("Copyright (c) 1999-2007 Intel Corporation. All rights reserved.\n");
}

static
void
Usage (
  VOID
  )
/*++

Routine Description:
  
  Print usage information for this utility.

Arguments:

  None.

Returns:

  Nothing.

--*/
{
  int               Index;
  static const char *Msg[] = {
    "\nUsage: "UTILITY_NAME " {-v} {-dump} {-h|-?} {-o OutFileName} InFileName",
    "                [-e|-b] [FileName(s)]",
    "    where:",
    "      -h,--help,-?,/?  to display help messages",
    "      -V,--version     to display version information",
    "      -v             - for verbose output",
    "      -dump          - to dump the input file to a text file",
    "      -o OutFileName - to write output to OutFileName rather than InFileName"DEFAULT_OUTPUT_EXTENSION,
    "      InFileName     - name of the input PE32 file",
    "",
    NULL
  };
  
  Version();
  
  for (Index = 0; Msg[Index] != NULL; Index++) {
    fprintf (stdout, "%s\n", Msg[Index]);
  }
}

static
VOID
DumpImage (
  INT8    *FileName
  )
/*++

Routine Description:
  
  Dump a specified image information

Arguments:
  
  FileName - File name pointer to the image to dump

Returns:

  Nothing.

--*/
{
  FILE                *InFptr;
  EFI_TE_IMAGE_HEADER TEImageHeader;
  INT8                *NamePtr;

  //
  // Open the input file
  //
  InFptr  = NULL;

  if ((InFptr = fopen (FileName, "rb")) == NULL) {
    Error (NULL, 0, 0, FileName, "failed to open input file for reading");
    return ;
  }

  if (fread (&TEImageHeader, sizeof (EFI_TE_IMAGE_HEADER), 1, InFptr) != 1) {
    Error (NULL, 0, 0, FileName, "failed to read image header from input file");
    goto Finish;
  }

  if (TEImageHeader.Signature != EFI_TE_IMAGE_HEADER_SIGNATURE) {
    Error (NULL, 0, 0, FileName, "Image does not appear to be a TE image (bad signature)");
    goto Finish;
  }
  //
  // Dump the header
  //
  fprintf (stdout, "Header (%d bytes):\n", sizeof (EFI_TE_IMAGE_HEADER));
  fprintf (stdout, "  Signature:          0x%04X (TE)\n", (UINT32) TEImageHeader.Signature);
  NamePtr = GetMachineTypeStr (TEImageHeader.Machine);
  fprintf (stdout, "  Machine:            0x%04X (%s)\n", (UINT32) TEImageHeader.Machine, NamePtr);
  NamePtr = GetSubsystemTypeStr (TEImageHeader.Subsystem);
  fprintf (stdout, "  Subsystem:          0x%02X (%s)\n", (UINT32) TEImageHeader.Subsystem, NamePtr);
  fprintf (stdout, "  Number of sections  0x%02X\n", (UINT32) TEImageHeader.NumberOfSections);
  fprintf (stdout, "  Stripped size:      0x%04X\n", (UINT32) TEImageHeader.StrippedSize);
  fprintf (stdout, "  Entry point:        0x%08X\n", TEImageHeader.AddressOfEntryPoint);
  fprintf (stdout, "  Base of code:       0x%08X\n", TEImageHeader.BaseOfCode);
  fprintf (stdout, "  Data directories:\n");
  fprintf (
    stdout,
    "    %8X [%8X] RVA [size] of Base Relocation Directory\n",
    TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress,
    TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size
    );
  fprintf (
    stdout,
    "    %8X [%8X] RVA [size] of Debug Directory\n",
    TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress,
    TEImageHeader.DataDirectory[EFI_TE_IMAGE_DIRECTORY_ENTRY_DEBUG].Size
    );

Finish:
  if (InFptr != NULL) {
    fclose (InFptr);
  }
}

static
INT8 *
GetMachineTypeStr (
  UINT16    MachineType
  )
/*++

Routine Description:

  GC_TODO: Add function description

Arguments:

  MachineType - GC_TODO: add argument description

Returns:

  GC_TODO: add return values

--*/
{
  int Index;

  for (Index = 0; mMachineTypes[Index].Name != NULL; Index++) {
    if (mMachineTypes[Index].Value == MachineType) {
      return mMachineTypes[Index].Name;
    }
  }

  return "unknown";
}

static
INT8 *
GetSubsystemTypeStr (
  UINT16  SubsystemType
  )
/*++

Routine Description:

  GC_TODO: Add function description

Arguments:

  SubsystemType - GC_TODO: add argument description

Returns:

  GC_TODO: add return values

--*/
{
  int Index;

  for (Index = 0; mSubsystemTypes[Index].Name != NULL; Index++) {
    if (mSubsystemTypes[Index].Value == SubsystemType) {
      return mSubsystemTypes[Index].Name;
    }
  }

  return "unknown";
}