File: Handle.c

package info (click to toggle)
edk2 0~20131112.2590861a-3
  • links: PTS, VCS
  • area: non-free
  • in suites: jessie, jessie-kfreebsd
  • size: 125,836 kB
  • ctags: 175,818
  • sloc: ansic: 1,274,042; python: 75,968; asm: 68,082; perl: 22,386; cpp: 22,278; makefile: 14,914; sh: 4,113; pascal: 1,126; xml: 318; lisp: 24
file content (1317 lines) | stat: -rw-r--r-- 34,753 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
/*++

Copyright (c) 2005 - 2013, 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:

    Handle.c

Abstract:

  The handle function
  
Revision History

--*/

#include "EfiShellLib.h"

EFI_STATUS
LibLocateHandle (
  IN EFI_LOCATE_SEARCH_TYPE       SearchType,
  IN EFI_GUID                     * Protocol OPTIONAL,
  IN VOID                         *SearchKey OPTIONAL,
  IN OUT UINTN                    *NoHandles,
  OUT EFI_HANDLE                  **Buffer
  )
/*++

Routine Description:

  Function returns an array of handles that support the requested protocol 
  in a buffer allocated from pool.

Arguments:

  SearchType           - Specifies which handle(s) are to be returned.
  Protocol             - Provides the protocol to search by.   
                         This parameter is only valid for SearchType ByProtocol.
  SearchKey            - Supplies the search key depending on the SearchType.
  NoHandles            - The number of handles returned in Buffer.
  Buffer               - A pointer to the buffer to return the requested array of 
                         handles that support Protocol.

Returns:
  
  EFI_SUCCESS           - The result array of handles was returned.
  EFI_NOT_FOUND         - No handles match the search. 
  EFI_OUT_OF_RESOURCES - There is not enough pool memory to store the matching results.

--*/
{
  EFI_STATUS  Status;
  UINTN       BufferSize;
  
  ASSERT (NoHandles != NULL);
  ASSERT (Buffer != NULL);

  //
  // Initialize for GrowBuffer loop
  //
  Status      = EFI_SUCCESS;
  *Buffer     = NULL;
  BufferSize  = 50 * sizeof (EFI_HANDLE);

  //
  // Call the real function
  //
  while (GrowBuffer (&Status, (VOID **) Buffer, BufferSize)) {
    Status = BS->LocateHandle (
                  SearchType,
                  Protocol,
                  SearchKey,
                  &BufferSize,
                  *Buffer
                  );
  }

  *NoHandles = BufferSize / sizeof (EFI_HANDLE);
  if (EFI_ERROR (Status)) {
    *NoHandles = 0;
  }

  return Status;
}

EFI_STATUS
LibLocateHandleByDiskSignature (
  IN UINT8                        MBRType,
  IN UINT8                        SignatureType,
  IN VOID                         *Signature,
  IN OUT UINTN                    *NoHandles,
  OUT EFI_HANDLE                  **Buffer
  )
/*++

Routine Description:

  Function returns an array of handles that support the requested protocol in 
  a buffer allocated from pool.

Arguments:

  MBRType              - Specifies the type of MBR to search for.  This can either 
                         be the PC AT compatible MBR or an EFI Partition Table Header.
  SignatureType        - Specifies the type of signature to look for in the MBR.  
                         This can either be a 32 bit signature, or a GUID signature.
  Signature            - A pointer to a 32 bit disk signature or a pointer to a GUID 
                         disk signature. The type depends on SignatureType.
  NoHandles            - The number of handles returned in Buffer.
  Buffer               - A pointer to the buffer to return the requested array of 
                         handles that support Protocol.

Returns:
  
  EFI_SUCCESS           - The result array of handles was returned.
  EFI_NOT_FOUND         - No handles match the search. 
  EFI_OUT_OF_RESOURCES - There is not enough pool memory to store the matching results.

--*/
{
  EFI_STATUS                Status;
  UINTN                     BufferSize;
  UINTN                     NoBlockIoHandles;
  EFI_HANDLE                *BlockIoBuffer;
  EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
  UINTN                     Index;
  EFI_DEVICE_PATH_PROTOCOL  *Next;
  EFI_DEVICE_PATH_PROTOCOL  *DevPath;
  HARDDRIVE_DEVICE_PATH     *HardDriveDevicePath;
  BOOLEAN                   Match;
  BOOLEAN                   PreviousNodeIsHardDriveDevicePath;

  ASSERT (NoHandles != NULL);
  ASSERT (Buffer != NULL);
  //
  // Initialize for GrowBuffer loop
  //
  BlockIoBuffer = NULL;
  BufferSize    = 50 * sizeof (EFI_HANDLE);

  //
  // Call the real function
  //
  while (GrowBuffer (&Status, (VOID **) &BlockIoBuffer, BufferSize)) {
    //
    // Get list of device handles that support the BLOCK_IO Protocol.
    //
    Status = BS->LocateHandle (
                  ByProtocol,
                  &gEfiBlockIoProtocolGuid,
                  NULL,
                  &BufferSize,
                  BlockIoBuffer
                  );
  }

  NoBlockIoHandles = BufferSize / sizeof (EFI_HANDLE);
  if (EFI_ERROR (Status)) {
    NoBlockIoHandles = 0;
  }
  //
  // If there was an error or there are no device handles that support
  // the BLOCK_IO Protocol, then return.
  //
  if (NoBlockIoHandles == 0) {
    ASSERT(BlockIoBuffer != NULL);
    FreePool (BlockIoBuffer);
    *NoHandles  = 0;
    *Buffer     = NULL;
    return Status;
  }
  //
  // Loop through all the device handles that support the BLOCK_IO Protocol
  //
  *NoHandles = 0;

  for (Index = 0; Index < NoBlockIoHandles; Index++) {

    Status = BS->HandleProtocol (
                  BlockIoBuffer[Index],
                  &gEfiDevicePathProtocolGuid,
                  (VOID *) &DevicePath
                  );

    //
    // Search DevicePath for a Hard Drive Media Device Path node.
    // If one is found, then see if it matches the signature that was
    // passed in.  If it does match, and the next node is the End of the
    // device path, and the previous node is not a Hard Drive Media Device
    // Path, then we have found a match.
    //
    Match = FALSE;

    if (DevicePath != NULL) {

      PreviousNodeIsHardDriveDevicePath = FALSE;

      DevPath = DevicePath;
      //
      // Check for end of device path type
      //
      for (;;) {

        if ((DevicePathType (DevPath) == MEDIA_DEVICE_PATH) && (DevicePathSubType (DevPath) == MEDIA_HARDDRIVE_DP)) {

          HardDriveDevicePath = (HARDDRIVE_DEVICE_PATH *) (DevPath);

          if (PreviousNodeIsHardDriveDevicePath == FALSE) {

            Next = NextDevicePathNode (DevPath);
            if (IsDevicePathEndType (Next)) {
              if ((HardDriveDevicePath->MBRType == MBRType) && (HardDriveDevicePath->SignatureType == SignatureType)) {
                switch (SignatureType) {
                case SIGNATURE_TYPE_MBR:
                  if (*((UINT32 *) (Signature)) == * (UINT32 *) (&(HardDriveDevicePath->Signature[0]))) {
                    Match = TRUE;
                  }
                  break;

                case SIGNATURE_TYPE_GUID:
                  if (CompareGuid ((EFI_GUID *) Signature, (EFI_GUID *) (&(HardDriveDevicePath->Signature[0]))) == 0) {
                    Match = TRUE;
                  }
                  break;
                }
              }
            }
          }

          PreviousNodeIsHardDriveDevicePath = TRUE;
        } else {
          PreviousNodeIsHardDriveDevicePath = FALSE;
        }

        if (IsDevicePathEnd (DevPath)) {
          break;
        }

        DevPath = NextDevicePathNode (DevPath);
      }

    }

    if (Match == FALSE) {
      BlockIoBuffer[Index] = NULL;
    } else {
      *NoHandles = *NoHandles + 1;
    }
  }
  //
  // If there are no matches, then return
  //
  if (*NoHandles == 0) {
    FreePool (BlockIoBuffer);
    *NoHandles  = 0;
    *Buffer     = NULL;
    return EFI_SUCCESS;
  }
  //
  // Allocate space for the return buffer of device handles.
  //
  *Buffer = AllocatePool (*NoHandles * sizeof (EFI_HANDLE));

  if (*Buffer == NULL) {
    FreePool (BlockIoBuffer);
    *NoHandles  = 0;
    *Buffer     = NULL;
    return EFI_OUT_OF_RESOURCES;
  }
  //
  // Build list of matching device handles.
  //
  *NoHandles = 0;
  for (Index = 0; Index < NoBlockIoHandles; Index++) {
    if (BlockIoBuffer[Index] != NULL) {
      (*Buffer)[*NoHandles] = BlockIoBuffer[Index];
      *NoHandles            = *NoHandles + 1;
    }
  }

  FreePool (BlockIoBuffer);

  return EFI_SUCCESS;
}

EFI_FILE_SYSTEM_INFO *
LibFileSystemInfo (
  IN EFI_FILE_HANDLE      FHand
  )
/*++

Routine Description:

  Function gets the file system information from an open file descriptor, 
  and stores it in a buffer allocated from pool.

Arguments:

  FHand         - A file handle

Returns:
  
  A pointer to a buffer with file information or NULL is returned

--*/
{
  EFI_STATUS            Status;
  EFI_FILE_SYSTEM_INFO  *Buffer;
  UINTN                 BufferSize;
  
  ASSERT (FHand != NULL);
  
  //
  // Initialize for GrowBuffer loop
  //
  Buffer      = NULL;
  BufferSize  = SIZE_OF_EFI_FILE_SYSTEM_INFO + 200;

  //
  // Call the real function
  //
  while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) {
    Status = FHand->GetInfo (
                      FHand,
                      &gEfiFileSystemInfoGuid,
                      &BufferSize,
                      Buffer
                      );
  }

  return Buffer;
}

EFI_FILE_SYSTEM_VOLUME_LABEL_INFO *
LibFileSystemVolumeLabelInfo (
  IN EFI_FILE_HANDLE      FHand
  )
/*++

Routine Description:

  Function gets the file system information from an open file descriptor, 
  and stores it in a buffer allocated from pool.

Arguments:

  FHand         - A file handle

Returns:
  
  A pointer to a buffer with file information or NULL is returned

--*/
{
  EFI_STATUS                        Status;
  EFI_FILE_SYSTEM_VOLUME_LABEL_INFO *Buffer;
  UINTN                             BufferSize;

  ASSERT (FHand != NULL);

  //
  // Initialize for GrowBuffer loop
  //
  Buffer      = NULL;
  BufferSize  = SIZE_OF_EFI_FILE_SYSTEM_VOLUME_LABEL_INFO + 200;

  //
  // Call the real function
  //
  while (GrowBuffer (&Status, (VOID **) &Buffer, BufferSize)) {
    Status = FHand->GetInfo (
                      FHand,
                      &gEfiFileSystemVolumeLabelInfoIdGuid,
                      &BufferSize,
                      Buffer
                      );
  }

  return Buffer;
}

EFI_STATUS
LibInstallProtocolInterfaces (
  IN OUT EFI_HANDLE             *Handle,
  ...
  )
/*++

Routine Description:

  Function installs one or more protocol interfaces into the boot services environment.

Arguments:

  Handle               - The handle to install the new protocol interfaces on, or NULL if a 
                         new handle is to be allocated.

  ...                  - A variable argument list containing pairs of protocol GUIDs and 
                         protocol interfaces.

Returns:
  
  EFI_SUCCESS           - All the protocol interfaces were installed.
  EFI_OUT_OF_RESOURCES - There was not enough memory in pool to install all the protocols.

--*/
{
  VA_LIST     args;
  EFI_STATUS  Status;
  EFI_GUID    *Protocol;
  VOID        *Interface;
  EFI_TPL     OldTpl;
  UINTN       Index;
  EFI_HANDLE  OldHandle;

  ASSERT (Handle);
  
  //
  // Syncronize with notifcations
  //
  OldTpl    = BS->RaiseTPL (EFI_TPL_NOTIFY);
  OldHandle = *Handle;

  //
  // Install the protocol interfaces
  //
  Index   = 0;
  Status  = EFI_SUCCESS;
  VA_START (args, Handle);

  while (!EFI_ERROR (Status)) {
    //
    // If protocol is NULL, then it's the end of the list
    //
    Protocol = VA_ARG (args, EFI_GUID *);
    if (!Protocol) {
      break;
    }

    Interface = VA_ARG (args, VOID *);

    //
    // Install it
    //
    BS->RestoreTPL (OldTpl);
    DEBUG ((EFI_D_INFO, "LibInstallProtocolInterface: %d %x\n", Protocol, Interface));
    BS->RaiseTPL (EFI_TPL_NOTIFY);

    Status = BS->InstallProtocolInterface (
                  Handle,
                  Protocol,
                  EFI_NATIVE_INTERFACE,
                  Interface
                  );
    if (EFI_ERROR (Status)) {
      break;
    }

    Index += 1;
  }
  //
  // If there was an error, remove all the interfaces that were
  // installed without any errors
  //
  if (EFI_ERROR (Status)) {
    VA_START (args, Handle);
    while (Index) {
      Protocol  = VA_ARG (args, EFI_GUID *);
      Interface = VA_ARG (args, VOID *);
      BS->UninstallProtocolInterface (
            *Handle,
            Protocol,
            Interface
            );
      Index -= 1;
    }

    *Handle = OldHandle;
  }
  //
  // Done
  //
  BS->RestoreTPL (OldTpl);
  return Status;
}

VOID
LibUninstallProtocolInterfaces (
  IN EFI_HANDLE             Handle,
  ...
  )
/*++

Routine Description:

  Function removes one or more protocol interfaces into the boot services environment.

Arguments:

  Handle               - The handle to remove the protocol interfaces from.

  ...                  - A variable argument list containing pairs of protocol GUIDs and 
                         protocol interfaces.

Returns:
  
  EFI_SUCCESS           - All the protocol interfaces were removed.
  EFI_OUT_OF_RESOURCES - One of the protocol interfaces could not be found.

--*/
{
  VA_LIST     args;
  EFI_STATUS  Status;
  EFI_GUID    *Protocol;
  VOID        *Interface;

  VA_START (args, Handle);
  for (;;) {
    //
    // If protocol is NULL, then it's the end of the list
    //
    Protocol = VA_ARG (args, EFI_GUID *);
    if (!Protocol) {
      break;
    }

    Interface = VA_ARG (args, VOID *);

    //
    // Uninstall it
    //
    Status = BS->UninstallProtocolInterface (Handle, Protocol, Interface);
    if (EFI_ERROR (Status)) {
      DEBUG ((EFI_D_ERROR, "LibUninstallProtocolInterfaces: failed %g, %x\n", Protocol, Handle));
    }
  }
}

EFI_STATUS
LibReinstallProtocolInterfaces (
  IN OUT EFI_HANDLE             *Handle,
  ...
  )
/*++

Routine Description:

  Function replaces one or more protocol interfaces into the boot services environment.

Arguments:

  Handle               - The handle to reinstall the protocol interfaces to.

  ...                  - A variable argument list containing pairs of protocol GUIDs and 
                         protocol interfaces.

Returns:
  
  EFI_SUCCESS           - All the protocol interfaces were replaced.
  EFI_OUT_OF_RESOURCES - One of the protocol interfaces could not be found.

--*/
{
  VA_LIST     args;
  EFI_STATUS  Status;
  EFI_GUID    *Protocol;
  VOID        *OldInterface;
  VOID        *NewInterface;
  EFI_TPL     OldTpl;
  UINTN       Index;

  //
  // Syncronize with notifcations
  //
  OldTpl = BS->RaiseTPL (EFI_TPL_NOTIFY);

  //
  // Install the protocol interfaces
  //
  Index   = 0;
  Status  = EFI_SUCCESS;
  VA_START (args, Handle);

  while (!EFI_ERROR (Status)) {
    //
    // If protocol is NULL, then it's the end of the list
    //
    Protocol = VA_ARG (args, EFI_GUID *);
    if (!Protocol) {
      break;
    }

    OldInterface  = VA_ARG (args, VOID *);
    NewInterface  = VA_ARG (args, VOID *);

    //
    // Reinstall it
    //
    Status = BS->ReinstallProtocolInterface (
                  Handle,
                  Protocol,
                  OldInterface,
                  NewInterface
                  );
    if (EFI_ERROR (Status)) {
      break;
    }

    Index += 1;
  }
  //
  // If there was an error, undo all the interfaces that were
  // reinstalled without any errors
  //
  if (EFI_ERROR (Status)) {
    VA_START (args, Handle);
    while (Index) {
      Protocol      = VA_ARG (args, EFI_GUID *);
      OldInterface  = VA_ARG (args, VOID *);
      NewInterface  = VA_ARG (args, VOID *);

      BS->ReinstallProtocolInterface (
            Handle,
            Protocol,
            NewInterface,
            OldInterface
            );

      Index -= 1;
    }
  }
  //
  // Done
  //
  BS->RestoreTPL (OldTpl);
  return Status;
}

UINTN
ShellHandleNoFromIndex (
  IN UINTN        Value
  )
{

  UINTN TotalHandleNo;
  UINTN HandleNo;

  TotalHandleNo = SE2->HandleEnumerator.GetNum ();

  HandleNo      = Value;
  HandleNo      = HandleNo > TotalHandleNo ? 0 : HandleNo;
  return HandleNo;

}

EFI_HANDLE
ShellHandleFromIndex (
  IN UINTN        Value
  )
/*++

Routine Description:

Arguments:

  Value   - The index

Returns:

--*/
{
  UINTN       HandleNo;
  UINTN       TotalHandleNo;
  UINTN       CurHandleNo;

  EFI_HANDLE  *Handle;

  CurHandleNo   = SE2->HandleEnumerator.Reset (0);
  TotalHandleNo = SE2->HandleEnumerator.GetNum ();
  HandleNo      = Value;

  if (HandleNo > TotalHandleNo - 1) {
    return NULL;

  }

  SE2->HandleEnumerator.Skip (HandleNo);
  SE2->HandleEnumerator.Next (&Handle);

  //
  // restore context
  //
  SE2->HandleEnumerator.Reset (CurHandleNo);
  return *Handle;
}

UINTN
ShellHandleToIndex (
  IN  EFI_HANDLE  Handle
  )
/*++

Routine Description:

Arguments:

  Handle - The handle

Returns:

--*/
{
  UINTN       Index;
  UINTN       TotalHandleNo;
  UINTN       CurHandleNo;

  EFI_HANDLE  *HandleIterator;

  CurHandleNo   = SE2->HandleEnumerator.Reset (0);

  TotalHandleNo = SE2->HandleEnumerator.GetNum ();

  for (Index = 0; Index < TotalHandleNo; Index++) {
    SE2->HandleEnumerator.Next (&HandleIterator);
    if (*HandleIterator == Handle) {
      //
      // restore context
      //
      CurHandleNo = SE2->HandleEnumerator.Reset (CurHandleNo);
      return Index + 1;
    }
  }
  //
  // restore context
  //
  SE2->HandleEnumerator.Reset (CurHandleNo);
  return 0;
}

UINTN
ShellHandleNoFromStr (
  IN CHAR16       *Str
  )
/*++

Routine Description:

Arguments:

  Str  - The string

Returns:

--*/
{
  UINTN HandleNo;
  UINTN TotalHandleNo;

  ASSERT (Str);
  
  HandleNo      = Xtoi (Str);
  TotalHandleNo = SE2->HandleEnumerator.GetNum ();

  HandleNo      = HandleNo > TotalHandleNo ? 0 : HandleNo;
  return HandleNo;
}

EFI_STATUS
LibScanHandleDatabase (
  EFI_HANDLE  DriverBindingHandle, OPTIONAL
  UINT32      *DriverBindingHandleIndex, OPTIONAL
  EFI_HANDLE  ControllerHandle, OPTIONAL
  UINT32      *ControllerHandleIndex, OPTIONAL
  UINTN       *HandleCount,
  EFI_HANDLE  **HandleBuffer,
  UINT32      **HandleType
  )

{
  EFI_STATUS                          Status;
  UINTN                               HandleIndex;
  EFI_GUID                            **ProtocolGuidArray;
  UINTN                               ArrayCount;
  UINTN                               ProtocolIndex;
  EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo;
  UINTN                               OpenInfoCount;
  UINTN                               OpenInfoIndex;
  UINTN                               ChildIndex;
  BOOLEAN                             DriverBindingHandleIndexValid;

  DriverBindingHandleIndexValid = FALSE;
  if (DriverBindingHandleIndex != NULL) {
    *DriverBindingHandleIndex = 0xffffffff;
  }

  if (ControllerHandleIndex != NULL) {
    *ControllerHandleIndex = 0xffffffff;
  }

  *HandleCount  = 0;
  *HandleBuffer = NULL;
  *HandleType   = NULL;

  //
  // Retrieve the list of all handles from the handle database
  //
  Status = BS->LocateHandleBuffer (
                AllHandles,
                NULL,
                NULL,
                HandleCount,
                HandleBuffer
                );
  if (EFI_ERROR (Status)) {
    goto Error;
  }

  *HandleType = AllocatePool (*HandleCount * sizeof (UINT32));
  if (*HandleType == NULL) {
    goto Error;
  }

  for (HandleIndex = 0; HandleIndex < *HandleCount; HandleIndex++) {
    //
    // Assume that the handle type is unknown
    //
    (*HandleType)[HandleIndex] = EFI_HANDLE_TYPE_UNKNOWN;

    if (DriverBindingHandle != NULL &&
        DriverBindingHandleIndex != NULL &&
        (*HandleBuffer)[HandleIndex] == DriverBindingHandle
        ) {
      *DriverBindingHandleIndex     = (UINT32) HandleIndex;
      DriverBindingHandleIndexValid = TRUE;
    }

    if (ControllerHandle != NULL && ControllerHandleIndex != NULL && (*HandleBuffer)[HandleIndex] == ControllerHandle) {
      *ControllerHandleIndex      = (UINT32) HandleIndex;
    }

  }

  for (HandleIndex = 0; HandleIndex < *HandleCount; HandleIndex++) {
    //
    // Retrieve the list of all the protocols on each handle
    //
    Status = BS->ProtocolsPerHandle (
                  (*HandleBuffer)[HandleIndex],
                  &ProtocolGuidArray,
                  &ArrayCount
                  );
    if (!EFI_ERROR (Status)) {

      for (ProtocolIndex = 0; ProtocolIndex < ArrayCount; ProtocolIndex++) {

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiLoadedImageProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_IMAGE_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDriverBindingProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DRIVER_BINDING_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDriverConfiguration2ProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DRIVER_CONFIGURATION_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDriverConfigurationProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DRIVER_CONFIGURATION_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDriverDiagnostics2ProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DRIVER_DIAGNOSTICS_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDriverDiagnosticsProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DRIVER_DIAGNOSTICS_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiComponentName2ProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_COMPONENT_NAME_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiComponentNameProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_COMPONENT_NAME_HANDLE;
        }

        if (CompareGuid (ProtocolGuidArray[ProtocolIndex], &gEfiDevicePathProtocolGuid) == 0) {
          (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_DEVICE_HANDLE;
        }
        //
        // Retrieve the list of agents that have opened each protocol
        //
        Status = BS->OpenProtocolInformation (
                      (*HandleBuffer)[HandleIndex],
                      ProtocolGuidArray[ProtocolIndex],
                      &OpenInfo,
                      &OpenInfoCount
                      );
        if (!EFI_ERROR (Status)) {

          for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) {
            if (DriverBindingHandle != NULL && OpenInfo[OpenInfoIndex].AgentHandle == DriverBindingHandle) {
              if ((OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) == EFI_OPEN_PROTOCOL_BY_DRIVER) {
                //
                // Mark the device handle as being managed by the driver specified by DriverBindingHandle
                //
                (*HandleType)[HandleIndex] |= (EFI_HANDLE_TYPE_DEVICE_HANDLE | EFI_HANDLE_TYPE_CONTROLLER_HANDLE);
                //
                // Mark the DriverBindingHandle as being a driver that is managing at least one controller
                //
                if (DriverBindingHandleIndexValid) {
                  (*HandleType)[*DriverBindingHandleIndex] |= EFI_HANDLE_TYPE_DEVICE_DRIVER;
                }
              }

              if ((
                    OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                ) == EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                  ) {
                //
                // Mark the device handle as being managed by the driver specified by DriverBindingHandle
                //
                (*HandleType)[HandleIndex] |= (EFI_HANDLE_TYPE_DEVICE_HANDLE | EFI_HANDLE_TYPE_CONTROLLER_HANDLE);
                //
                // Mark the DriverBindingHandle as being a driver that is managing at least one child controller
                //
                if (DriverBindingHandleIndexValid) {
                  (*HandleType)[*DriverBindingHandleIndex] |= EFI_HANDLE_TYPE_BUS_DRIVER;
                }
              }

              if (ControllerHandle != NULL && (*HandleBuffer)[HandleIndex] == ControllerHandle) {
                if ((
                      OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                  ) == EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                    ) {
                  for (ChildIndex = 0; ChildIndex < *HandleCount; ChildIndex++) {
                    if ((*HandleBuffer)[ChildIndex] == OpenInfo[OpenInfoIndex].ControllerHandle) {
                      (*HandleType)[ChildIndex] |= (EFI_HANDLE_TYPE_DEVICE_HANDLE | EFI_HANDLE_TYPE_CHILD_HANDLE);
                    }
                  }
                }
              }
            }

            if (DriverBindingHandle == NULL && (*HandleBuffer)[HandleIndex] == ControllerHandle) {
              if ((OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) == EFI_OPEN_PROTOCOL_BY_DRIVER) {
                for (ChildIndex = 0; ChildIndex < *HandleCount; ChildIndex++) {
                  if ((*HandleBuffer)[ChildIndex] == OpenInfo[OpenInfoIndex].AgentHandle) {
                    (*HandleType)[ChildIndex] |= EFI_HANDLE_TYPE_DEVICE_DRIVER;
                  }
                }
              }
              if ((
                    OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                ) == EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                  ) {
                for (ChildIndex = 0; ChildIndex < *HandleCount; ChildIndex++) {
                  if ((*HandleBuffer)[ChildIndex] == OpenInfo[OpenInfoIndex].AgentHandle) {
                    (*HandleType)[ChildIndex] |= (EFI_HANDLE_TYPE_BUS_DRIVER | EFI_HANDLE_TYPE_DEVICE_DRIVER);
                  }
                  if ((*HandleBuffer)[ChildIndex] == OpenInfo[OpenInfoIndex].ControllerHandle) {
                    (*HandleType)[ChildIndex] |= (EFI_HANDLE_TYPE_DEVICE_HANDLE | EFI_HANDLE_TYPE_CHILD_HANDLE);
                  }
                }
              }
            }

            if (DriverBindingHandle == NULL && OpenInfo[OpenInfoIndex].ControllerHandle == ControllerHandle) {
              if ((
                    OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                ) == EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                  ) {
                (*HandleType)[HandleIndex] |= EFI_HANDLE_TYPE_PARENT_HANDLE;
                for (ChildIndex = 0; ChildIndex < *HandleCount; ChildIndex++) {
                  if ((*HandleBuffer)[ChildIndex] == OpenInfo[OpenInfoIndex].AgentHandle) {
                    (*HandleType)[ChildIndex] |= EFI_HANDLE_TYPE_BUS_DRIVER;
                  }
                }
              }
            }
          }

          FreePool (OpenInfo);
        }
      }

      FreePool (ProtocolGuidArray);
    }
  }

  return EFI_SUCCESS;

Error:
  if (*HandleType != NULL) {
    FreePool (*HandleType);
  }

  if (*HandleBuffer != NULL) {
    FreePool (*HandleBuffer);
  }

  *HandleCount  = 0;
  *HandleBuffer = NULL;
  *HandleType   = NULL;

  return Status;
}

EFI_STATUS
LibGetHandleDatabaseSubset (
  EFI_HANDLE  DriverBindingHandle,
  EFI_HANDLE  ControllerHandle,
  UINT32      Mask,
  UINTN       *MatchingHandleCount,
  EFI_HANDLE  **MatchingHandleBuffer
  )

{
  EFI_STATUS  Status;
  UINTN       HandleCount;
  EFI_HANDLE  *HandleBuffer;
  UINT32      *HandleType;
  UINTN       HandleIndex;

  ASSERT (MatchingHandleCount != NULL);

  *MatchingHandleCount = 0;
  if (MatchingHandleBuffer != NULL) {
    *MatchingHandleBuffer = NULL;
  }

  HandleBuffer  = NULL;
  HandleType    = NULL;

  Status = LibScanHandleDatabase (
            DriverBindingHandle,
            NULL,
            ControllerHandle,
            NULL,
            &HandleCount,
            &HandleBuffer,
            &HandleType
            );
  if (EFI_ERROR (Status)) {
    goto Done;
  }
  //
  // Count the number of handles that match the attributes in Mask
  //
  for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
    if ((HandleType[HandleIndex] & Mask) == Mask) {
      (*MatchingHandleCount)++;
    }
  }
  //
  // If no handles match the attributes in Mask then return EFI_NOT_FOUND
  //
  if (*MatchingHandleCount == 0) {
    Status = EFI_NOT_FOUND;
    goto Done;
  }

  if (MatchingHandleBuffer == NULL) {
    Status = EFI_SUCCESS;
    goto Done;
  }
  //
  // Allocate a handle buffer for the number of handles that matched the attributes in Mask
  //
  *MatchingHandleBuffer = AllocatePool (*MatchingHandleCount * sizeof (EFI_HANDLE));
  if (*MatchingHandleBuffer == NULL) {
    goto Done;
  }
  //
  // Fill the allocated buffer with the handles that matched the attributes in Mask
  //
  *MatchingHandleCount = 0;
  for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
    if ((HandleType[HandleIndex] & Mask) == Mask) {
      (*MatchingHandleBuffer)[(*MatchingHandleCount)++] = HandleBuffer[HandleIndex];
    }
  }

  Status = EFI_SUCCESS;

Done:
  //
  // Free the buffers alocated by LibScanHandleDatabase()
  //
  if (HandleBuffer != NULL) {
    FreePool (HandleBuffer);
  }

  if (HandleType != NULL) {
    FreePool (HandleType);
  }

  return Status;
}

EFI_STATUS
LibGetManagingDriverBindingHandles (
  EFI_HANDLE  ControllerHandle,
  UINTN       *DriverBindingHandleCount,
  EFI_HANDLE  **DriverBindingHandleBuffer
  )

{
  return LibGetHandleDatabaseSubset (
          NULL,
          ControllerHandle,
          EFI_HANDLE_TYPE_DRIVER_BINDING_HANDLE | EFI_HANDLE_TYPE_DEVICE_DRIVER,
          DriverBindingHandleCount,
          DriverBindingHandleBuffer
          );
}

EFI_STATUS
LibGetParentControllerHandles (
  EFI_HANDLE  ControllerHandle,
  UINTN       *ParentControllerHandleCount,
  EFI_HANDLE  **ParentControllerHandleBuffer
  )

{
  return LibGetHandleDatabaseSubset (
          NULL,
          ControllerHandle,
          EFI_HANDLE_TYPE_PARENT_HANDLE,
          ParentControllerHandleCount,
          ParentControllerHandleBuffer
          );
}

EFI_STATUS
LibGetManagedChildControllerHandles (
  EFI_HANDLE  DriverBindingHandle,
  EFI_HANDLE  ControllerHandle,
  UINTN       *ChildControllerHandleCount,
  EFI_HANDLE  **ChildControllerHandleBuffer
  )

{
  return LibGetHandleDatabaseSubset (
          DriverBindingHandle,
          ControllerHandle,
          EFI_HANDLE_TYPE_CHILD_HANDLE | EFI_HANDLE_TYPE_DEVICE_HANDLE,
          ChildControllerHandleCount,
          ChildControllerHandleBuffer
          );
}

EFI_STATUS
LibGetManagedControllerHandles (
  EFI_HANDLE  DriverBindingHandle,
  UINTN       *ControllerHandleCount,
  EFI_HANDLE  **ControllerHandleBuffer
  )

{
  return LibGetHandleDatabaseSubset (
          DriverBindingHandle,
          NULL,
          EFI_HANDLE_TYPE_CONTROLLER_HANDLE | EFI_HANDLE_TYPE_DEVICE_HANDLE,
          ControllerHandleCount,
          ControllerHandleBuffer
          );
}

EFI_STATUS
LibGetChildControllerHandles (
  EFI_HANDLE  ControllerHandle,
  UINTN       *HandleCount,
  EFI_HANDLE  **HandleBuffer
  )

{
  EFI_STATUS  Status;
  UINTN       HandleIndex;
  UINTN       DriverBindingHandleCount;
  EFI_HANDLE  *DriverBindingHandleBuffer;
  UINTN       DriverBindingHandleIndex;
  UINTN       ChildControllerHandleCount;
  EFI_HANDLE  *ChildControllerHandleBuffer;
  UINTN       ChildControllerHandleIndex;
  BOOLEAN     Found;
  
  ASSERT (HandleCount != NULL);
  ASSERT (HandleBuffer != NULL);

  *HandleCount  = 0;
  *HandleBuffer = NULL;

  Status = LibGetManagingDriverBindingHandles (
            ControllerHandle,
            &DriverBindingHandleCount,
            &DriverBindingHandleBuffer
            );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  Status = BS->LocateHandleBuffer (
                AllHandles,
                NULL,
                NULL,
                HandleCount,
                HandleBuffer
                );
  if (EFI_ERROR (Status)) {
    FreePool (DriverBindingHandleBuffer);
    return Status;
  }

  *HandleCount = 0;
  for (DriverBindingHandleIndex = 0; DriverBindingHandleIndex < DriverBindingHandleCount; DriverBindingHandleIndex++) {
    Status = LibGetManagedChildControllerHandles (
              DriverBindingHandleBuffer[DriverBindingHandleIndex],
              ControllerHandle,
              &ChildControllerHandleCount,
              &ChildControllerHandleBuffer
              );
    if (EFI_ERROR (Status)) {
      continue;
    }

    for (ChildControllerHandleIndex = 0;
         ChildControllerHandleIndex < ChildControllerHandleCount;
         ChildControllerHandleIndex++
        ) {
      Found = FALSE;
      for (HandleIndex = 0; HandleIndex < *HandleCount; HandleIndex++) {
        if ((*HandleBuffer)[HandleIndex] == ChildControllerHandleBuffer[ChildControllerHandleIndex]) {
          Found = TRUE;
        }
      }

      if (!Found) {
        (*HandleBuffer)[(*HandleCount)++] = ChildControllerHandleBuffer[ChildControllerHandleIndex];
      }
    }

    FreePool (ChildControllerHandleBuffer);
  }

  FreePool (DriverBindingHandleBuffer);

  return EFI_SUCCESS;
}

EFI_STATUS
LibLocateProtocol (
  IN  EFI_GUID    *ProtocolGuid,
  OUT VOID        **Interface
  )
/*++

Routine Description:

  Find the first instance of this Protocol in the system and return it's interface

Arguments:

  ProtocolGuid    - Provides the protocol to search for
  Interface       - On return, a pointer to the first interface that matches ProtocolGuid

Returns:

  EFI_SUCCESS     - A protocol instance matching ProtocolGuid was found

  EFI_NOT_FOUND   - No protocol instances were found that match ProtocolGuid

--*/
{
  EFI_STATUS  Status;
  UINTN       NumberHandles;
  UINTN       Index;
  EFI_HANDLE  *Handles;

  *Interface    = NULL;
  Handles       = NULL;
  NumberHandles = 0;

  Status        = LibLocateHandle (ByProtocol, ProtocolGuid, NULL, &NumberHandles, &Handles);
  if (EFI_ERROR (Status)) {
    DEBUG ((EFI_D_INFO, "LibLocateProtocol: Handle not found\n"));
    return Status;
  }

  for (Index = 0; Index < NumberHandles; Index++) {
    Status = BS->HandleProtocol (
                  Handles[Index],
                  ProtocolGuid,
                  (VOID**)Interface
                  );

    if (!EFI_ERROR (Status)) {
      break;
    }
  }

  if (Handles) {
    FreePool (Handles);
  }

  return Status;
}