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