]> code.delx.au - refind/blob - refind/lib.c
Looks for refind_linux.conf first, then linux.conf, for Linux kernel configuration...
[refind] / refind / lib.c
1 /*
2 * refit/lib.c
3 * General library functions
4 *
5 * Copyright (c) 2006-2009 Christoph Pfisterer
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are
10 * met:
11 *
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * * Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the
18 * distribution.
19 *
20 * * Neither the name of Christoph Pfisterer nor the names of the
21 * contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 */
36 /*
37 * Modifications copyright (c) 2012 Roderick W. Smith
38 *
39 * Modifications distributed under the terms of the GNU General Public
40 * License (GPL) version 3 (GPLv3), a copy of which must be distributed
41 * with this source code or binaries made from it.
42 *
43 */
44
45 #include "global.h"
46 #include "lib.h"
47 #include "icns.h"
48 #include "screen.h"
49 #include "refit_call_wrapper.h"
50
51 // variables
52
53 EFI_HANDLE SelfImageHandle;
54 EFI_LOADED_IMAGE *SelfLoadedImage;
55 EFI_FILE *SelfRootDir;
56 EFI_FILE *SelfDir;
57 CHAR16 *SelfDirPath;
58
59 REFIT_VOLUME *SelfVolume = NULL;
60 REFIT_VOLUME **Volumes = NULL;
61 UINTN VolumesCount = 0;
62
63 // Maximum size for disk sectors
64 #define SECTOR_SIZE 4096
65
66 // functions
67
68 static EFI_STATUS FinishInitRefitLib(VOID);
69
70 static VOID UninitVolumes(VOID);
71
72 //
73 // self recognition stuff
74 //
75
76 EFI_STATUS InitRefitLib(IN EFI_HANDLE ImageHandle)
77 {
78 EFI_STATUS Status;
79 CHAR16 *DevicePathAsString;
80 CHAR16 BaseDirectory[256];
81 UINTN i;
82
83 SelfImageHandle = ImageHandle;
84 Status = refit_call3_wrapper(BS->HandleProtocol, SelfImageHandle, &LoadedImageProtocol, (VOID **) &SelfLoadedImage);
85 if (CheckFatalError(Status, L"while getting a LoadedImageProtocol handle"))
86 return EFI_LOAD_ERROR;
87
88 // find the current directory
89 DevicePathAsString = DevicePathToStr(SelfLoadedImage->FilePath);
90 if (DevicePathAsString != NULL) {
91 StrCpy(BaseDirectory, DevicePathAsString);
92 FreePool(DevicePathAsString);
93 for (i = StrLen(BaseDirectory); i > 0 && BaseDirectory[i] != '\\'; i--) ;
94 BaseDirectory[i] = 0;
95 } else
96 BaseDirectory[0] = 0;
97 SelfDirPath = StrDuplicate(BaseDirectory);
98
99 return FinishInitRefitLib();
100 }
101
102 // called before running external programs to close open file handles
103 VOID UninitRefitLib(VOID)
104 {
105 UninitVolumes();
106
107 if (SelfDir != NULL) {
108 refit_call1_wrapper(SelfDir->Close, SelfDir);
109 SelfDir = NULL;
110 }
111
112 if (SelfRootDir != NULL) {
113 refit_call1_wrapper(SelfRootDir->Close, SelfRootDir);
114 SelfRootDir = NULL;
115 }
116 }
117
118 // called after running external programs to re-open file handles
119 EFI_STATUS ReinitRefitLib(VOID)
120 {
121 ReinitVolumes();
122
123 if (SelfVolume != NULL && SelfVolume->RootDir != NULL)
124 SelfRootDir = SelfVolume->RootDir;
125
126 return FinishInitRefitLib();
127 }
128
129 static EFI_STATUS FinishInitRefitLib(VOID)
130 {
131 EFI_STATUS Status;
132
133 if (SelfRootDir == NULL) {
134 SelfRootDir = LibOpenRoot(SelfLoadedImage->DeviceHandle);
135 if (SelfRootDir == NULL) {
136 CheckError(EFI_LOAD_ERROR, L"while (re)opening our installation volume");
137 return EFI_LOAD_ERROR;
138 }
139 }
140
141 Status = refit_call5_wrapper(SelfRootDir->Open, SelfRootDir, &SelfDir, SelfDirPath, EFI_FILE_MODE_READ, 0);
142 if (CheckFatalError(Status, L"while opening our installation directory"))
143 return EFI_LOAD_ERROR;
144
145 return EFI_SUCCESS;
146 }
147
148 //
149 // list functions
150 //
151
152 VOID CreateList(OUT VOID ***ListPtr, OUT UINTN *ElementCount, IN UINTN InitialElementCount)
153 {
154 UINTN AllocateCount;
155
156 *ElementCount = InitialElementCount;
157 if (*ElementCount > 0) {
158 AllocateCount = (*ElementCount + 7) & ~7; // next multiple of 8
159 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
160 } else {
161 *ListPtr = NULL;
162 }
163 }
164
165 VOID AddListElement(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount, IN VOID *NewElement)
166 {
167 UINTN AllocateCount;
168
169 if ((*ElementCount & 7) == 0) {
170 AllocateCount = *ElementCount + 8;
171 if (*ElementCount == 0)
172 *ListPtr = AllocatePool(sizeof(VOID *) * AllocateCount);
173 else
174 *ListPtr = ReallocatePool(*ListPtr, sizeof(VOID *) * (*ElementCount), sizeof(VOID *) * AllocateCount);
175 }
176 (*ListPtr)[*ElementCount] = NewElement;
177 (*ElementCount)++;
178 } /* VOID AddListElement() */
179
180 VOID FreeList(IN OUT VOID ***ListPtr, IN OUT UINTN *ElementCount)
181 {
182 UINTN i;
183
184 if (*ElementCount > 0) {
185 for (i = 0; i < *ElementCount; i++) {
186 // TODO: call a user-provided routine for each element here
187 FreePool((*ListPtr)[i]);
188 }
189 FreePool(*ListPtr);
190 }
191 }
192
193 //
194 // firmware device path discovery
195 //
196
197 static UINT8 LegacyLoaderMediaPathData[] = {
198 0x04, 0x06, 0x14, 0x00, 0xEB, 0x85, 0x05, 0x2B,
199 0xB8, 0xD8, 0xA9, 0x49, 0x8B, 0x8C, 0xE2, 0x1B,
200 0x01, 0xAE, 0xF2, 0xB7, 0x7F, 0xFF, 0x04, 0x00,
201 };
202 static EFI_DEVICE_PATH *LegacyLoaderMediaPath = (EFI_DEVICE_PATH *)LegacyLoaderMediaPathData;
203
204 VOID ExtractLegacyLoaderPaths(EFI_DEVICE_PATH **PathList, UINTN MaxPaths, EFI_DEVICE_PATH **HardcodedPathList)
205 {
206 EFI_STATUS Status;
207 UINTN HandleCount = 0;
208 UINTN HandleIndex, HardcodedIndex;
209 EFI_HANDLE *Handles;
210 EFI_HANDLE Handle;
211 UINTN PathCount = 0;
212 UINTN PathIndex;
213 EFI_LOADED_IMAGE *LoadedImage;
214 EFI_DEVICE_PATH *DevicePath;
215 BOOLEAN Seen;
216
217 MaxPaths--; // leave space for the terminating NULL pointer
218
219 // get all LoadedImage handles
220 Status = LibLocateHandle(ByProtocol, &LoadedImageProtocol, NULL,
221 &HandleCount, &Handles);
222 if (CheckError(Status, L"while listing LoadedImage handles")) {
223 if (HardcodedPathList) {
224 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
225 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
226 }
227 PathList[PathCount] = NULL;
228 return;
229 }
230 for (HandleIndex = 0; HandleIndex < HandleCount && PathCount < MaxPaths; HandleIndex++) {
231 Handle = Handles[HandleIndex];
232
233 Status = refit_call3_wrapper(BS->HandleProtocol, Handle, &LoadedImageProtocol, (VOID **) &LoadedImage);
234 if (EFI_ERROR(Status))
235 continue; // This can only happen if the firmware scewed up, ignore it.
236
237 Status = refit_call3_wrapper(BS->HandleProtocol, LoadedImage->DeviceHandle, &DevicePathProtocol, (VOID **) &DevicePath);
238 if (EFI_ERROR(Status))
239 continue; // This happens, ignore it.
240
241 // Only grab memory range nodes
242 if (DevicePathType(DevicePath) != HARDWARE_DEVICE_PATH || DevicePathSubType(DevicePath) != HW_MEMMAP_DP)
243 continue;
244
245 // Check if we have this device path in the list already
246 // WARNING: This assumes the first node in the device path is unique!
247 Seen = FALSE;
248 for (PathIndex = 0; PathIndex < PathCount; PathIndex++) {
249 if (DevicePathNodeLength(DevicePath) != DevicePathNodeLength(PathList[PathIndex]))
250 continue;
251 if (CompareMem(DevicePath, PathList[PathIndex], DevicePathNodeLength(DevicePath)) == 0) {
252 Seen = TRUE;
253 break;
254 }
255 }
256 if (Seen)
257 continue;
258
259 PathList[PathCount++] = AppendDevicePath(DevicePath, LegacyLoaderMediaPath);
260 }
261 FreePool(Handles);
262
263 if (HardcodedPathList) {
264 for (HardcodedIndex = 0; HardcodedPathList[HardcodedIndex] && PathCount < MaxPaths; HardcodedIndex++)
265 PathList[PathCount++] = HardcodedPathList[HardcodedIndex];
266 }
267 PathList[PathCount] = NULL;
268 }
269
270 //
271 // volume functions
272 //
273
274 static VOID ScanVolumeBootcode(IN OUT REFIT_VOLUME *Volume, OUT BOOLEAN *Bootable)
275 {
276 EFI_STATUS Status;
277 UINT8 SectorBuffer[SECTOR_SIZE];
278 UINTN i;
279 MBR_PARTITION_INFO *MbrTable;
280 BOOLEAN MbrTableFound;
281
282 Volume->HasBootCode = FALSE;
283 Volume->OSIconName = NULL;
284 Volume->OSName = NULL;
285 *Bootable = FALSE;
286
287 if (Volume->BlockIO == NULL)
288 return;
289 if (Volume->BlockIO->Media->BlockSize > SECTOR_SIZE)
290 return; // our buffer is too small...
291
292 // look at the boot sector (this is used for both hard disks and El Torito images!)
293 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
294 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
295 Volume->BlockIOOffset, SECTOR_SIZE, SectorBuffer);
296 if (!EFI_ERROR(Status)) {
297
298 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55 && SectorBuffer[0] != 0) {
299 *Bootable = TRUE;
300 Volume->HasBootCode = TRUE;
301 }
302
303 // detect specific boot codes
304 if (CompareMem(SectorBuffer + 2, "LILO", 4) == 0 ||
305 CompareMem(SectorBuffer + 6, "LILO", 4) == 0 ||
306 CompareMem(SectorBuffer + 3, "SYSLINUX", 8) == 0 ||
307 FindMem(SectorBuffer, SECTOR_SIZE, "ISOLINUX", 8) >= 0) {
308 Volume->HasBootCode = TRUE;
309 Volume->OSIconName = L"linux";
310 Volume->OSName = L"Linux";
311
312 } else if (FindMem(SectorBuffer, 512, "Geom\0Hard Disk\0Read\0 Error", 26) >= 0) { // GRUB
313 Volume->HasBootCode = TRUE;
314 Volume->OSIconName = L"grub,linux";
315 Volume->OSName = L"Linux";
316
317 } else if ((*((UINT32 *)(SectorBuffer + 502)) == 0 &&
318 *((UINT32 *)(SectorBuffer + 506)) == 50000 &&
319 *((UINT16 *)(SectorBuffer + 510)) == 0xaa55) ||
320 FindMem(SectorBuffer, SECTOR_SIZE, "Starting the BTX loader", 23) >= 0) {
321 Volume->HasBootCode = TRUE;
322 Volume->OSIconName = L"freebsd";
323 Volume->OSName = L"FreeBSD";
324
325 } else if (FindMem(SectorBuffer, 512, "!Loading", 8) >= 0 ||
326 FindMem(SectorBuffer, SECTOR_SIZE, "/cdboot\0/CDBOOT\0", 16) >= 0) {
327 Volume->HasBootCode = TRUE;
328 Volume->OSIconName = L"openbsd";
329 Volume->OSName = L"OpenBSD";
330
331 } else if (FindMem(SectorBuffer, 512, "Not a bootxx image", 18) >= 0 ||
332 *((UINT32 *)(SectorBuffer + 1028)) == 0x7886b6d1) {
333 Volume->HasBootCode = TRUE;
334 Volume->OSIconName = L"netbsd";
335 Volume->OSName = L"NetBSD";
336
337 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "NTLDR", 5) >= 0) {
338 Volume->HasBootCode = TRUE;
339 Volume->OSIconName = L"win";
340 Volume->OSName = L"Windows";
341
342 } else if (FindMem(SectorBuffer, SECTOR_SIZE, "BOOTMGR", 7) >= 0) {
343 Volume->HasBootCode = TRUE;
344 Volume->OSIconName = L"winvista,win";
345 Volume->OSName = L"Windows";
346
347 } else if (FindMem(SectorBuffer, 512, "CPUBOOT SYS", 11) >= 0 ||
348 FindMem(SectorBuffer, 512, "KERNEL SYS", 11) >= 0) {
349 Volume->HasBootCode = TRUE;
350 Volume->OSIconName = L"freedos";
351 Volume->OSName = L"FreeDOS";
352
353 } else if (FindMem(SectorBuffer, 512, "OS2LDR", 6) >= 0 ||
354 FindMem(SectorBuffer, 512, "OS2BOOT", 7) >= 0) {
355 Volume->HasBootCode = TRUE;
356 Volume->OSIconName = L"ecomstation";
357 Volume->OSName = L"eComStation";
358
359 } else if (FindMem(SectorBuffer, 512, "Be Boot Loader", 14) >= 0) {
360 Volume->HasBootCode = TRUE;
361 Volume->OSIconName = L"beos";
362 Volume->OSName = L"BeOS";
363
364 } else if (FindMem(SectorBuffer, 512, "yT Boot Loader", 14) >= 0) {
365 Volume->HasBootCode = TRUE;
366 Volume->OSIconName = L"zeta,beos";
367 Volume->OSName = L"ZETA";
368
369 } else if (FindMem(SectorBuffer, 512, "\x04" "beos\x06" "system\x05" "zbeos", 18) >= 0 ||
370 FindMem(SectorBuffer, 512, "\x06" "system\x0c" "haiku_loader", 20) >= 0) {
371 Volume->HasBootCode = TRUE;
372 Volume->OSIconName = L"haiku,beos";
373 Volume->OSName = L"Haiku";
374
375 }
376
377 // NOTE: If you add an operating system with a name that starts with 'W' or 'L', you
378 // need to fix AddLegacyEntry in main.c.
379
380 #if REFIT_DEBUG > 0
381 Print(L" Result of bootcode detection: %s %s (%s)\n",
382 Volume->HasBootCode ? L"bootable" : L"non-bootable",
383 Volume->OSName, Volume->OSIconName);
384 #endif
385
386 if (FindMem(SectorBuffer, 512, "Non-system disk", 15) >= 0) // dummy FAT boot sector
387 Volume->HasBootCode = FALSE;
388
389 // check for MBR partition table
390 if (*((UINT16 *)(SectorBuffer + 510)) == 0xaa55) {
391 MbrTableFound = FALSE;
392 MbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
393 for (i = 0; i < 4; i++)
394 if (MbrTable[i].StartLBA && MbrTable[i].Size)
395 MbrTableFound = TRUE;
396 for (i = 0; i < 4; i++)
397 if (MbrTable[i].Flags != 0x00 && MbrTable[i].Flags != 0x80)
398 MbrTableFound = FALSE;
399 if (MbrTableFound) {
400 Volume->MbrPartitionTable = AllocatePool(4 * 16);
401 CopyMem(Volume->MbrPartitionTable, MbrTable, 4 * 16);
402 }
403 }
404
405 } else {
406 #if REFIT_DEBUG > 0
407 CheckError(Status, L"while reading boot sector");
408 #endif
409 }
410 }
411
412 // default volume icon based on disk kind
413 static VOID ScanVolumeDefaultIcon(IN OUT REFIT_VOLUME *Volume)
414 {
415 switch (Volume->DiskKind) {
416 case DISK_KIND_INTERNAL:
417 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_INTERNAL);
418 break;
419 case DISK_KIND_EXTERNAL:
420 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_EXTERNAL);
421 break;
422 case DISK_KIND_OPTICAL:
423 Volume->VolBadgeImage = BuiltinIcon(BUILTIN_ICON_VOL_OPTICAL);
424 break;
425 } // switch()
426 }
427
428 static VOID ScanVolume(IN OUT REFIT_VOLUME *Volume)
429 {
430 EFI_STATUS Status;
431 EFI_DEVICE_PATH *DevicePath, *NextDevicePath;
432 EFI_DEVICE_PATH *DiskDevicePath, *RemainingDevicePath;
433 EFI_HANDLE WholeDiskHandle;
434 UINTN PartialLength;
435 EFI_FILE_SYSTEM_INFO *FileSystemInfoPtr;
436 BOOLEAN Bootable;
437
438 // get device path
439 Volume->DevicePath = DuplicateDevicePath(DevicePathFromHandle(Volume->DeviceHandle));
440 #if REFIT_DEBUG > 0
441 if (Volume->DevicePath != NULL) {
442 Print(L"* %s\n", DevicePathToStr(Volume->DevicePath));
443 #if REFIT_DEBUG >= 2
444 DumpHex(1, 0, DevicePathSize(Volume->DevicePath), Volume->DevicePath);
445 #endif
446 }
447 #endif
448
449 Volume->DiskKind = DISK_KIND_INTERNAL; // default
450
451 // get block i/o
452 Status = refit_call3_wrapper(BS->HandleProtocol, Volume->DeviceHandle, &BlockIoProtocol, (VOID **) &(Volume->BlockIO));
453 if (EFI_ERROR(Status)) {
454 Volume->BlockIO = NULL;
455 Print(L"Warning: Can't get BlockIO protocol.\n");
456 } else {
457 if (Volume->BlockIO->Media->BlockSize == 2048)
458 Volume->DiskKind = DISK_KIND_OPTICAL;
459 }
460
461 // scan for bootcode and MBR table
462 Bootable = FALSE;
463 ScanVolumeBootcode(Volume, &Bootable);
464
465 // detect device type
466 DevicePath = Volume->DevicePath;
467 while (DevicePath != NULL && !IsDevicePathEndType(DevicePath)) {
468 NextDevicePath = NextDevicePathNode(DevicePath);
469
470 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH &&
471 (DevicePathSubType(DevicePath) == MSG_USB_DP ||
472 DevicePathSubType(DevicePath) == MSG_USB_CLASS_DP ||
473 DevicePathSubType(DevicePath) == MSG_1394_DP ||
474 DevicePathSubType(DevicePath) == MSG_FIBRECHANNEL_DP))
475 Volume->DiskKind = DISK_KIND_EXTERNAL; // USB/FireWire/FC device -> external
476 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH &&
477 DevicePathSubType(DevicePath) == MEDIA_CDROM_DP) {
478 Volume->DiskKind = DISK_KIND_OPTICAL; // El Torito entry -> optical disk
479 Bootable = TRUE;
480 }
481
482 if (DevicePathType(DevicePath) == MEDIA_DEVICE_PATH && DevicePathSubType(DevicePath) == MEDIA_VENDOR_DP) {
483 Volume->IsAppleLegacy = TRUE; // legacy BIOS device entry
484 // TODO: also check for Boot Camp GUID
485 Bootable = FALSE; // this handle's BlockIO is just an alias for the whole device
486 }
487
488 if (DevicePathType(DevicePath) == MESSAGING_DEVICE_PATH) {
489 // make a device path for the whole device
490 PartialLength = (UINT8 *)NextDevicePath - (UINT8 *)(Volume->DevicePath);
491 DiskDevicePath = (EFI_DEVICE_PATH *)AllocatePool(PartialLength + sizeof(EFI_DEVICE_PATH));
492 CopyMem(DiskDevicePath, Volume->DevicePath, PartialLength);
493 CopyMem((UINT8 *)DiskDevicePath + PartialLength, EndDevicePath, sizeof(EFI_DEVICE_PATH));
494
495 // get the handle for that path
496 RemainingDevicePath = DiskDevicePath;
497 //Print(L" * looking at %s\n", DevicePathToStr(RemainingDevicePath));
498 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
499 //Print(L" * remaining: %s\n", DevicePathToStr(RemainingDevicePath));
500 FreePool(DiskDevicePath);
501
502 if (!EFI_ERROR(Status)) {
503 //Print(L" - original handle: %08x - disk handle: %08x\n", (UINT32)DeviceHandle, (UINT32)WholeDiskHandle);
504
505 // get the device path for later
506 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &DevicePathProtocol, (VOID **) &DiskDevicePath);
507 if (!EFI_ERROR(Status)) {
508 Volume->WholeDiskDevicePath = DuplicateDevicePath(DiskDevicePath);
509 }
510
511 // look at the BlockIO protocol
512 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
513 if (!EFI_ERROR(Status)) {
514
515 // check the media block size
516 if (Volume->WholeDiskBlockIO->Media->BlockSize == 2048)
517 Volume->DiskKind = DISK_KIND_OPTICAL;
518
519 } else {
520 Volume->WholeDiskBlockIO = NULL;
521 //CheckError(Status, L"from HandleProtocol");
522 }
523 } //else
524 // CheckError(Status, L"from LocateDevicePath");
525 }
526
527 DevicePath = NextDevicePath;
528 } // while
529
530 if (!Bootable) {
531 #if REFIT_DEBUG > 0
532 if (Volume->HasBootCode)
533 Print(L" Volume considered non-bootable, but boot code is present\n");
534 #endif
535 Volume->HasBootCode = FALSE;
536 }
537
538 // default volume icon based on disk kind
539 ScanVolumeDefaultIcon(Volume);
540
541 // open the root directory of the volume
542 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
543 if (Volume->RootDir == NULL) {
544 return;
545 }
546
547 // get volume name
548 FileSystemInfoPtr = LibFileSystemInfo(Volume->RootDir);
549 if (FileSystemInfoPtr != NULL) {
550 Volume->VolName = StrDuplicate(FileSystemInfoPtr->VolumeLabel);
551 FreePool(FileSystemInfoPtr);
552 }
553
554 // TODO: if no official volume name is found or it is empty, use something else, e.g.:
555 // - name from bytes 3 to 10 of the boot sector
556 // - partition number
557 // - name derived from file system type or partition type
558
559 // get custom volume icon if present
560 if (FileExists(Volume->RootDir, L".VolumeIcon.icns"))
561 Volume->VolBadgeImage = LoadIcns(Volume->RootDir, L".VolumeIcon.icns", 32);
562 }
563
564 static VOID ScanExtendedPartition(REFIT_VOLUME *WholeDiskVolume, MBR_PARTITION_INFO *MbrEntry)
565 {
566 EFI_STATUS Status;
567 REFIT_VOLUME *Volume;
568 UINT32 ExtBase, ExtCurrent, NextExtCurrent;
569 UINTN i;
570 UINTN LogicalPartitionIndex = 4;
571 UINT8 SectorBuffer[512];
572 BOOLEAN Bootable;
573 MBR_PARTITION_INFO *EMbrTable;
574
575 ExtBase = MbrEntry->StartLBA;
576
577 for (ExtCurrent = ExtBase; ExtCurrent; ExtCurrent = NextExtCurrent) {
578 // read current EMBR
579 Status = refit_call5_wrapper(WholeDiskVolume->BlockIO->ReadBlocks,
580 WholeDiskVolume->BlockIO,
581 WholeDiskVolume->BlockIO->Media->MediaId,
582 ExtCurrent, 512, SectorBuffer);
583 if (EFI_ERROR(Status))
584 break;
585 if (*((UINT16 *)(SectorBuffer + 510)) != 0xaa55)
586 break;
587 EMbrTable = (MBR_PARTITION_INFO *)(SectorBuffer + 446);
588
589 // scan logical partitions in this EMBR
590 NextExtCurrent = 0;
591 for (i = 0; i < 4; i++) {
592 if ((EMbrTable[i].Flags != 0x00 && EMbrTable[i].Flags != 0x80) ||
593 EMbrTable[i].StartLBA == 0 || EMbrTable[i].Size == 0)
594 break;
595 if (IS_EXTENDED_PART_TYPE(EMbrTable[i].Type)) {
596 // set next ExtCurrent
597 NextExtCurrent = ExtBase + EMbrTable[i].StartLBA;
598 break;
599 } else {
600
601 // found a logical partition
602 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
603 Volume->DiskKind = WholeDiskVolume->DiskKind;
604 Volume->IsMbrPartition = TRUE;
605 Volume->MbrPartitionIndex = LogicalPartitionIndex++;
606 Volume->VolName = PoolPrint(L"Partition %d", Volume->MbrPartitionIndex + 1);
607 Volume->BlockIO = WholeDiskVolume->BlockIO;
608 Volume->BlockIOOffset = ExtCurrent + EMbrTable[i].StartLBA;
609 Volume->WholeDiskBlockIO = WholeDiskVolume->BlockIO;
610
611 Bootable = FALSE;
612 ScanVolumeBootcode(Volume, &Bootable);
613 if (!Bootable)
614 Volume->HasBootCode = FALSE;
615
616 ScanVolumeDefaultIcon(Volume);
617
618 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
619
620 }
621 }
622 }
623 }
624
625 VOID ScanVolumes(VOID)
626 {
627 EFI_STATUS Status;
628 UINTN HandleCount = 0;
629 UINTN HandleIndex;
630 EFI_HANDLE *Handles;
631 REFIT_VOLUME *Volume, *WholeDiskVolume;
632 UINTN VolumeIndex, VolumeIndex2;
633 MBR_PARTITION_INFO *MbrTable;
634 UINTN PartitionIndex;
635 UINT8 *SectorBuffer1, *SectorBuffer2;
636 UINTN SectorSum, i;
637
638 FreePool(Volumes);
639 Volumes = NULL;
640 VolumesCount = 0;
641
642 // get all filesystem handles
643 Status = LibLocateHandle(ByProtocol, &BlockIoProtocol, NULL, &HandleCount, &Handles);
644 // was: &FileSystemProtocol
645 if (Status == EFI_NOT_FOUND)
646 return; // no filesystems. strange, but true...
647 if (CheckError(Status, L"while listing all file systems"))
648 return;
649
650 // first pass: collect information about all handles
651 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
652 Volume = AllocateZeroPool(sizeof(REFIT_VOLUME));
653 Volume->DeviceHandle = Handles[HandleIndex];
654 ScanVolume(Volume);
655
656 AddListElement((VOID ***) &Volumes, &VolumesCount, Volume);
657
658 if (Volume->DeviceHandle == SelfLoadedImage->DeviceHandle)
659 SelfVolume = Volume;
660 }
661 FreePool(Handles);
662
663 if (SelfVolume == NULL)
664 Print(L"WARNING: SelfVolume not found");
665
666 // second pass: relate partitions and whole disk devices
667 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
668 Volume = Volumes[VolumeIndex];
669 // check MBR partition table for extended partitions
670 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
671 Volume->BlockIO == Volume->WholeDiskBlockIO && Volume->BlockIOOffset == 0 &&
672 Volume->MbrPartitionTable != NULL) {
673 MbrTable = Volume->MbrPartitionTable;
674 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
675 if (IS_EXTENDED_PART_TYPE(MbrTable[PartitionIndex].Type)) {
676 ScanExtendedPartition(Volume, MbrTable + PartitionIndex);
677 }
678 }
679 }
680
681 // search for corresponding whole disk volume entry
682 WholeDiskVolume = NULL;
683 if (Volume->BlockIO != NULL && Volume->WholeDiskBlockIO != NULL &&
684 Volume->BlockIO != Volume->WholeDiskBlockIO) {
685 for (VolumeIndex2 = 0; VolumeIndex2 < VolumesCount; VolumeIndex2++) {
686 if (Volumes[VolumeIndex2]->BlockIO == Volume->WholeDiskBlockIO &&
687 Volumes[VolumeIndex2]->BlockIOOffset == 0)
688 WholeDiskVolume = Volumes[VolumeIndex2];
689 }
690 }
691
692 if (WholeDiskVolume != NULL && WholeDiskVolume->MbrPartitionTable != NULL) {
693 // check if this volume is one of the partitions in the table
694 MbrTable = WholeDiskVolume->MbrPartitionTable;
695 SectorBuffer1 = AllocatePool(512);
696 SectorBuffer2 = AllocatePool(512);
697 for (PartitionIndex = 0; PartitionIndex < 4; PartitionIndex++) {
698 // check size
699 if ((UINT64)(MbrTable[PartitionIndex].Size) != Volume->BlockIO->Media->LastBlock + 1)
700 continue;
701
702 // compare boot sector read through offset vs. directly
703 Status = refit_call5_wrapper(Volume->BlockIO->ReadBlocks,
704 Volume->BlockIO, Volume->BlockIO->Media->MediaId,
705 Volume->BlockIOOffset, 512, SectorBuffer1);
706 if (EFI_ERROR(Status))
707 break;
708 Status = refit_call5_wrapper(Volume->WholeDiskBlockIO->ReadBlocks,
709 Volume->WholeDiskBlockIO, Volume->WholeDiskBlockIO->Media->MediaId,
710 MbrTable[PartitionIndex].StartLBA, 512, SectorBuffer2);
711 if (EFI_ERROR(Status))
712 break;
713 if (CompareMem(SectorBuffer1, SectorBuffer2, 512) != 0)
714 continue;
715 SectorSum = 0;
716 for (i = 0; i < 512; i++)
717 SectorSum += SectorBuffer1[i];
718 if (SectorSum < 1000)
719 continue;
720
721 // TODO: mark entry as non-bootable if it is an extended partition
722
723 // now we're reasonably sure the association is correct...
724 Volume->IsMbrPartition = TRUE;
725 Volume->MbrPartitionIndex = PartitionIndex;
726 if (Volume->VolName == NULL)
727 Volume->VolName = PoolPrint(L"Partition %d", PartitionIndex + 1);
728 break;
729 }
730
731 FreePool(SectorBuffer1);
732 FreePool(SectorBuffer2);
733 }
734
735 }
736 } /* VOID ScanVolumes() */
737
738 static VOID UninitVolumes(VOID)
739 {
740 REFIT_VOLUME *Volume;
741 UINTN VolumeIndex;
742
743 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
744 Volume = Volumes[VolumeIndex];
745
746 if (Volume->RootDir != NULL) {
747 refit_call1_wrapper(Volume->RootDir->Close, Volume->RootDir);
748 Volume->RootDir = NULL;
749 }
750
751 Volume->DeviceHandle = NULL;
752 Volume->BlockIO = NULL;
753 Volume->WholeDiskBlockIO = NULL;
754 }
755 }
756
757 VOID ReinitVolumes(VOID)
758 {
759 EFI_STATUS Status;
760 REFIT_VOLUME *Volume;
761 UINTN VolumeIndex;
762 EFI_DEVICE_PATH *RemainingDevicePath;
763 EFI_HANDLE DeviceHandle, WholeDiskHandle;
764
765 for (VolumeIndex = 0; VolumeIndex < VolumesCount; VolumeIndex++) {
766 Volume = Volumes[VolumeIndex];
767
768 if (Volume->DevicePath != NULL) {
769 // get the handle for that path
770 RemainingDevicePath = Volume->DevicePath;
771 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &DeviceHandle);
772
773 if (!EFI_ERROR(Status)) {
774 Volume->DeviceHandle = DeviceHandle;
775
776 // get the root directory
777 Volume->RootDir = LibOpenRoot(Volume->DeviceHandle);
778
779 } else
780 CheckError(Status, L"from LocateDevicePath");
781 }
782
783 if (Volume->WholeDiskDevicePath != NULL) {
784 // get the handle for that path
785 RemainingDevicePath = Volume->WholeDiskDevicePath;
786 Status = refit_call3_wrapper(BS->LocateDevicePath, &BlockIoProtocol, &RemainingDevicePath, &WholeDiskHandle);
787
788 if (!EFI_ERROR(Status)) {
789 // get the BlockIO protocol
790 Status = refit_call3_wrapper(BS->HandleProtocol, WholeDiskHandle, &BlockIoProtocol, (VOID **) &Volume->WholeDiskBlockIO);
791 if (EFI_ERROR(Status)) {
792 Volume->WholeDiskBlockIO = NULL;
793 CheckError(Status, L"from HandleProtocol");
794 }
795 } else
796 CheckError(Status, L"from LocateDevicePath");
797 }
798 }
799 }
800
801 //
802 // file and dir functions
803 //
804
805 BOOLEAN FileExists(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath)
806 {
807 EFI_STATUS Status;
808 EFI_FILE_HANDLE TestFile;
809
810 Status = refit_call5_wrapper(BaseDir->Open, BaseDir, &TestFile, RelativePath, EFI_FILE_MODE_READ, 0);
811 if (Status == EFI_SUCCESS) {
812 refit_call1_wrapper(TestFile->Close, TestFile);
813 return TRUE;
814 }
815 return FALSE;
816 }
817
818 EFI_STATUS DirNextEntry(IN EFI_FILE *Directory, IN OUT EFI_FILE_INFO **DirEntry, IN UINTN FilterMode)
819 {
820 EFI_STATUS Status;
821 VOID *Buffer;
822 UINTN LastBufferSize, BufferSize;
823 INTN IterCount;
824
825 for (;;) {
826
827 // free pointer from last call
828 if (*DirEntry != NULL) {
829 FreePool(*DirEntry);
830 *DirEntry = NULL;
831 }
832
833 // read next directory entry
834 LastBufferSize = BufferSize = 256;
835 Buffer = AllocatePool(BufferSize);
836 for (IterCount = 0; ; IterCount++) {
837 Status = refit_call3_wrapper(Directory->Read, Directory, &BufferSize, Buffer);
838 if (Status != EFI_BUFFER_TOO_SMALL || IterCount >= 4)
839 break;
840 if (BufferSize <= LastBufferSize) {
841 Print(L"FS Driver requests bad buffer size %d (was %d), using %d instead\n", BufferSize, LastBufferSize, LastBufferSize * 2);
842 BufferSize = LastBufferSize * 2;
843 #if REFIT_DEBUG > 0
844 } else {
845 Print(L"Reallocating buffer from %d to %d\n", LastBufferSize, BufferSize);
846 #endif
847 }
848 Buffer = ReallocatePool(Buffer, LastBufferSize, BufferSize);
849 LastBufferSize = BufferSize;
850 }
851 if (EFI_ERROR(Status)) {
852 FreePool(Buffer);
853 break;
854 }
855
856 // check for end of listing
857 if (BufferSize == 0) { // end of directory listing
858 FreePool(Buffer);
859 break;
860 }
861
862 // entry is ready to be returned
863 *DirEntry = (EFI_FILE_INFO *)Buffer;
864
865 // filter results
866 if (FilterMode == 1) { // only return directories
867 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY))
868 break;
869 } else if (FilterMode == 2) { // only return files
870 if (((*DirEntry)->Attribute & EFI_FILE_DIRECTORY) == 0)
871 break;
872 } else // no filter or unknown filter -> return everything
873 break;
874
875 }
876 return Status;
877 }
878
879 VOID DirIterOpen(IN EFI_FILE *BaseDir, IN CHAR16 *RelativePath OPTIONAL, OUT REFIT_DIR_ITER *DirIter)
880 {
881 if (RelativePath == NULL) {
882 DirIter->LastStatus = EFI_SUCCESS;
883 DirIter->DirHandle = BaseDir;
884 DirIter->CloseDirHandle = FALSE;
885 } else {
886 DirIter->LastStatus = refit_call5_wrapper(BaseDir->Open, BaseDir, &(DirIter->DirHandle), RelativePath, EFI_FILE_MODE_READ, 0);
887 DirIter->CloseDirHandle = EFI_ERROR(DirIter->LastStatus) ? FALSE : TRUE;
888 }
889 DirIter->LastFileInfo = NULL;
890 }
891
892 BOOLEAN DirIterNext(IN OUT REFIT_DIR_ITER *DirIter, IN UINTN FilterMode, IN CHAR16 *FilePattern OPTIONAL,
893 OUT EFI_FILE_INFO **DirEntry)
894 {
895 if (DirIter->LastFileInfo != NULL) {
896 FreePool(DirIter->LastFileInfo);
897 DirIter->LastFileInfo = NULL;
898 }
899
900 if (EFI_ERROR(DirIter->LastStatus))
901 return FALSE; // stop iteration
902
903 for (;;) {
904 DirIter->LastStatus = DirNextEntry(DirIter->DirHandle, &(DirIter->LastFileInfo), FilterMode);
905 if (EFI_ERROR(DirIter->LastStatus))
906 return FALSE;
907 if (DirIter->LastFileInfo == NULL) // end of listing
908 return FALSE;
909 if (FilePattern != NULL) {
910 if ((DirIter->LastFileInfo->Attribute & EFI_FILE_DIRECTORY))
911 break;
912 if (MetaiMatch(DirIter->LastFileInfo->FileName, FilePattern))
913 break;
914 // else continue loop
915 } else
916 break;
917 }
918
919 *DirEntry = DirIter->LastFileInfo;
920 return TRUE;
921 }
922
923 EFI_STATUS DirIterClose(IN OUT REFIT_DIR_ITER *DirIter)
924 {
925 if (DirIter->LastFileInfo != NULL) {
926 FreePool(DirIter->LastFileInfo);
927 DirIter->LastFileInfo = NULL;
928 }
929 if (DirIter->CloseDirHandle)
930 refit_call1_wrapper(DirIter->DirHandle->Close, DirIter->DirHandle);
931 return DirIter->LastStatus;
932 }
933
934 //
935 // file name manipulation
936 //
937
938 // Returns the filename portion (minus path name) of the
939 // specified file
940 CHAR16 * Basename(IN CHAR16 *Path)
941 {
942 CHAR16 *FileName;
943 UINTN i;
944
945 FileName = Path;
946
947 if (Path != NULL) {
948 for (i = StrLen(Path); i > 0; i--) {
949 if (Path[i-1] == '\\' || Path[i-1] == '/') {
950 FileName = Path + i;
951 break;
952 }
953 }
954 }
955
956 return FileName;
957 }
958
959 VOID ReplaceExtension(IN OUT CHAR16 *Path, IN CHAR16 *Extension)
960 {
961 UINTN i;
962
963 for (i = StrLen(Path); i >= 0; i--) {
964 if (Path[i] == '.') {
965 Path[i] = 0;
966 break;
967 }
968 if (Path[i] == '\\' || Path[i] == '/')
969 break;
970 }
971 StrCat(Path, Extension);
972 }
973
974 //
975 // memory string search
976 //
977
978 INTN FindMem(IN VOID *Buffer, IN UINTN BufferLength, IN VOID *SearchString, IN UINTN SearchStringLength)
979 {
980 UINT8 *BufferPtr;
981 UINTN Offset;
982
983 BufferPtr = Buffer;
984 BufferLength -= SearchStringLength;
985 for (Offset = 0; Offset < BufferLength; Offset++, BufferPtr++) {
986 if (CompareMem(BufferPtr, SearchString, SearchStringLength) == 0)
987 return (INTN)Offset;
988 }
989
990 return -1;
991 }
992
993 // Performs a case-insensitive search of BigStr for SmallStr.
994 // Returns TRUE if found, FALSE if not.
995 BOOLEAN StriSubCmp(IN CHAR16 *SmallStr, IN CHAR16 *BigStr) {
996 CHAR16 *SmallCopy, *BigCopy;
997 BOOLEAN Found = FALSE;
998 UINTN StartPoint = 0, NumCompares = 0, SmallLen = 0;
999
1000 if ((SmallStr != NULL) && (BigStr != NULL) && (StrLen(BigStr) >= StrLen(SmallStr))) {
1001 SmallCopy = StrDuplicate(SmallStr);
1002 BigCopy = StrDuplicate(BigStr);
1003 StrLwr(SmallCopy);
1004 StrLwr(BigCopy);
1005 SmallLen = StrLen(SmallCopy);
1006 NumCompares = StrLen(BigCopy) - SmallLen + 1;
1007 while ((!Found) && (StartPoint < NumCompares)) {
1008 Found = (StrnCmp(SmallCopy, &BigCopy[StartPoint++], SmallLen) == 0);
1009 } // while
1010 FreePool(SmallCopy);
1011 FreePool(BigCopy);
1012 } // if
1013
1014 return (Found);
1015 } // BOOLEAN StriSubCmp()
1016
1017 // Merges two strings, creating a new one and returning a pointer to it.
1018 // If AddChar != 0, the specified character is placed between the two original
1019 // strings (unless the first string is NULL). The original input string
1020 // *First is de-allocated and replaced by the new merged string.
1021 // This is similar to StrCat, but safer and more flexible because
1022 // MergeStrings allocates memory that's the correct size for the
1023 // new merged string, so it can take a NULL *First and it cleans
1024 // up the old memory. It should *NOT* be used with a constant
1025 // *First, though....
1026 VOID MergeStrings(IN OUT CHAR16 **First, IN CHAR16 *Second, CHAR16 AddChar) {
1027 UINTN Length1 = 0, Length2 = 0;
1028 CHAR16* NewString;
1029
1030 if (*First != NULL)
1031 Length1 = StrLen(*First);
1032 if (Second != NULL)
1033 Length2 = StrLen(Second);
1034 NewString = AllocatePool(sizeof(CHAR16) * (Length1 + Length2 + 2));
1035 NewString[0] = 0;
1036 if (NewString != NULL) {
1037 if (*First != NULL) {
1038 StrCat(NewString, *First);
1039 if (AddChar) {
1040 NewString[Length1] = AddChar;
1041 NewString[Length1 + 1] = 0;
1042 } // if (AddChar)
1043 } // if (First != NULL)
1044 if (First != NULL)
1045 StrCat(NewString, Second);
1046 FreePool(*First);
1047 *First = NewString;
1048 } else {
1049 Print(L"Error! Unable to allocate memory in MergeStrings()!\n");
1050 } // if/else
1051 } // static CHAR16* MergeStrings()
1052
1053 // Takes an input pathname (*Path) and locates the final directory component
1054 // of that name. For instance, if the input path is 'EFI\foo\bar.efi', this
1055 // function returns the string 'foo'.
1056 // Assumes the pathname is separated with backslashes.
1057 CHAR16 *FindLastDirName(IN CHAR16 *Path) {
1058 UINTN i, StartOfElement = 0, EndOfElement = 0, PathLength, CopyLength;
1059 CHAR16 *Found = NULL;
1060
1061 PathLength = StrLen(Path);
1062 // Find start & end of target element
1063 for (i = 0; i < PathLength; i++) {
1064 if (Path[i] == '\\') {
1065 StartOfElement = EndOfElement;
1066 EndOfElement = i;
1067 } // if
1068 } // for
1069 // Extract the target element
1070 if (EndOfElement > 0) {
1071 while ((StartOfElement < PathLength) && (Path[StartOfElement] == '\\')) {
1072 StartOfElement++;
1073 } // while
1074 EndOfElement--;
1075 if (EndOfElement >= StartOfElement) {
1076 CopyLength = EndOfElement - StartOfElement + 1;
1077 Found = StrDuplicate(&Path[StartOfElement]);
1078 if (Found != NULL)
1079 Found[CopyLength] = 0;
1080 } // if (EndOfElement >= StartOfElement)
1081 } // if (EndOfElement > 0)
1082 return (Found);
1083 } // CHAR16 *FindLastDirName
1084
1085 // Returns the directory portion of a pathname. For instance,
1086 // if FullPath is 'EFI\foo\bar.efi', this function returns the
1087 // string 'EFI\foo'.
1088 CHAR16 *FindPath(IN CHAR16* FullPath) {
1089 UINTN i, LastBackslash = 0;
1090 CHAR16 *PathOnly;
1091
1092 for (i = 0; i < StrLen(FullPath); i++) {
1093 if (FullPath[i] == '\\')
1094 LastBackslash = i;
1095 } // for
1096 PathOnly = StrDuplicate(FullPath);
1097 PathOnly[LastBackslash] = 0;
1098 return (PathOnly);
1099 }
1100
1101 // Returns all the digits in the input string, including intervening
1102 // non-digit characters. For instance, if InString is "foo-3.3.4-7.img",
1103 // this function returns "3.3.4-7". If InString contains no digits,
1104 // the return value is NULL.
1105 CHAR16 *FindNumbers(IN CHAR16 *InString) {
1106 UINTN i, StartOfElement, EndOfElement = 0, InLength, CopyLength;
1107 CHAR16 *Found = NULL;
1108
1109 InLength = StartOfElement = StrLen(InString);
1110 // Find start & end of target element
1111 for (i = 0; i < InLength; i++) {
1112 if ((InString[i] >= '0') && (InString[i] <= '9')) {
1113 if (StartOfElement > i)
1114 StartOfElement = i;
1115 if (EndOfElement < i)
1116 EndOfElement = i;
1117 } // if
1118 } // for
1119 // Extract the target element
1120 if (EndOfElement > 0) {
1121 if (EndOfElement >= StartOfElement) {
1122 CopyLength = EndOfElement - StartOfElement + 1;
1123 Found = StrDuplicate(&InString[StartOfElement]);
1124 if (Found != NULL)
1125 Found[CopyLength] = 0;
1126 } // if (EndOfElement >= StartOfElement)
1127 } // if (EndOfElement > 0)
1128 return (Found);
1129 } // CHAR16 *FindNumbers()
1130
1131 // Find the #Index element (numbered from 0) in a comma-delimited string
1132 // of elements.
1133 // Returns the found element, or NULL if Index is out of range of InString
1134 // is NULL.
1135 CHAR16 *FindCommaDelimited(IN CHAR16 *InString, IN UINTN Index) {
1136 UINTN StartPos = 0, CurPos = 0;
1137 BOOLEAN Found = FALSE;
1138 CHAR16 *FoundString = NULL;
1139
1140 if (InString != NULL) {
1141 // After while() loop, StartPos marks start of item #Index
1142 while ((Index > 0) && (CurPos < StrLen(InString))) {
1143 if (InString[CurPos] == L',') {
1144 Index--;
1145 StartPos = CurPos + 1;
1146 } // if
1147 CurPos++;
1148 } // while
1149 // After while() loop, CurPos is one past the end of the element
1150 while ((CurPos < StrLen(InString)) && (!Found)) {
1151 if (InString[CurPos] == L',')
1152 Found = TRUE;
1153 else
1154 CurPos++;
1155 } // while
1156 } // if
1157 if (Index == 0)
1158 FoundString = StrDuplicate(&InString[StartPos]);
1159 if (FoundString != NULL)
1160 FoundString[CurPos - StartPos] = 0;
1161 return (FoundString);
1162 } // CHAR16 *FindCommaDelimited()