From 048c5bf23c1ec62138f05a4a4a6900211a540de9 Mon Sep 17 00:00:00 2001 From: chris1111 Date: Thu, 19 Sep 2024 22:33:10 -0400 Subject: [PATCH] Update Credits on source code --- rEFIt_UEFI/refit/main.cpp | 5795 ++++++++++++++++++++++--------------- rEFIt_UEFI/refit/menu.cpp | 3 + 2 files changed, 3454 insertions(+), 2344 deletions(-) diff --git a/rEFIt_UEFI/refit/main.cpp b/rEFIt_UEFI/refit/main.cpp index 5f26aa81e..02bd0028e 100644 --- a/rEFIt_UEFI/refit/main.cpp +++ b/rEFIt_UEFI/refit/main.cpp @@ -1,8 +1,8 @@ /* - * refit/menu.c - * Menu functions + * refit/main.c + * Main code for the boot menu * - * Copyright (c) 2006 Christoph Pfisterer + * Copyright (c) 2006-2010 Christoph Pfisterer * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -34,2573 +34,3680 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "menu.h" #include // Only use angled for Platform, else, xcode project won't compile -#include "../libeg/libegint.h" +#include +#include -#include "../Platform/Settings.h" +#include "../cpp_foundation/XString.h" +#include "../cpp_lib/MemoryTracker.h" +#include "../cpp_unit_test/all_tests.h" +#include "../entry_scan/entry_scan.h" #include "../libeg/nanosvg.h" -#include "../libeg/FloatLib.h" -#include "../Platform/HdaCodecDump.h" +#include "../gui/menu_items/menu_globals.h" #include "menu.h" +#include "../Platform/Utils.h" +#include "../Platform/Settings.h" +#include "../Platform/DataHubCpu.h" +#include "../Platform/Events.h" #include "screen.h" -#include "../cpp_foundation/XString.h" -#include "../libeg/XTheme.h" -#include "../libeg/VectorGraphics.h" // for testSVG +#include "../entry_scan/bootscreen.h" +#include "../Platform/Nvram.h" +#include "../entry_scan/common.h" #include "../gui/shared_with_menu.h" #include "../Platform/platformdata.h" +#include "../Platform/guid.h" +#include "../Platform/APFS.h" #include "../Platform/cpu.h" -#include "../Platform/Nvram.h" -#include "../include/DsdtFixList.h" -#include "../include/Devices.h" -#include "../include/QuirksCodes.h" -#include "../Platform/boot.h" +#include "../Platform/smbios.h" +#include "../Platform/AcpiPatcher.h" +#include "../Platform/Hibernate.h" +#include "../Platform/LegacyBoot.h" +#include "../Platform/PlatformDriverOverride.h" +#include "../Platform/Edid.h" +#include "../Platform/Console.h" +#include "../Platform/spd.h" #include "../Platform/Injectors.h" +#include "../Platform/StartupSound.h" +#include "../Platform/BootOptions.h" +#include "../Platform/boot.h" +#include "../Platform/kext_inject.h" +#include "../Platform/device_inject.h" #include "../Platform/KextList.h" #include "../gui/REFIT_MENU_SCREEN.h" #include "../gui/REFIT_MAINMENU_SCREEN.h" #include "../Settings/Self.h" -#include "../Platform/VersionString.h" +#include "../Settings/SelfOem.h" +#include "../Platform/BasicIO.h" +#include "../include/OSTypes.h" +#include "../include/OSFlags.h" +#include "../libeg/XTheme.h" #include "../Settings/ConfigManager.h" #include "../Platform/CloverVersion.h" +#include "../Platform/SmbiosFillPatchingValues.h" + +#include "../include/OC.h" + #ifndef DEBUG_ALL -#define DEBUG_MENU 1 +# ifdef DEBUG_ERALY_CRASH +# define DEBUG_MAIN 2 +# else +# define DEBUG_MAIN 1 +# endif #else -#define DEBUG_MENU DEBUG_ALL +# define DEBUG_MAIN DEBUG_ALL #endif -#if DEBUG_MENU == 0 +#if DEBUG_MAIN == 0 #define DBG(...) #else -#define DBG(...) DebugLog(DEBUG_MENU, __VA_ARGS__) +#define DBG(...) DebugLog(DEBUG_MAIN, __VA_ARGS__) #endif +#ifndef HIBERNATE +#define HIBERNATE 0 +#endif -INTN LayoutMainMenuHeight = 376; -INTN LayoutAnimMoveForMenuX = 0; -#define TEXT_CORNER_REVISION (1) -#define TEXT_CORNER_HELP (2) -#define TEXT_CORNER_OPTIMUS (3) +#ifndef CHECK_SMC +#define CHECK_SMC 0 +#endif -REFIT_MENU_ITEM_OPTIONS MenuEntryOptions (L"Options"_XSW, 1, 0, 'O', ActionEnter); -REFIT_MENU_ITEM_ABOUT MenuEntryAbout (L"About Clover"_XSW, 1, 0, 'A', ActionEnter); -REFIT_MENU_ITEM_RESET MenuEntryReset (L"Restart Computer"_XSW, 1, 0, 'R', ActionSelect); -REFIT_MENU_ITEM_SHUTDOWN MenuEntryShutdown(L"Exit Clover"_XSW, 1, 0, 'U', ActionSelect); -REFIT_MENU_ITEM_RETURN MenuEntryReturn (L"Return"_XSW, 0, 0, 0, ActionEnter); -REFIT_MAINMENU_SCREEN MainMenu(1, L"Main Menu"_XSW, L"Automatic boot"_XSW); -REFIT_MENU_SCREEN AboutMenu(2, L"About"_XSW, L""_XSW); -REFIT_MENU_SCREEN HelpMenu(3, L"Help"_XSW, L""_XSW); -REFIT_MENU_SCREEN OptionMenu(4, L"Options"_XSW, L""_XSW); +#define PCAT_RTC_ADDRESS_REGISTER 0x70 +#define PCAT_RTC_DATA_REGISTER 0x71 -XBool gResetSMC = false; -extern APPLE_SMC_IO_PROTOCOL *gAppleSmc; -extern ConfigManager gConf; +// variables -void FillInputs(XBool New) -{ - UINTN i,j; //for loops - CHAR8 tmp[41]; - - tmp[40] = 0; //make it null-terminated - - UINTN InputItemsCount = 0; - - InputItems[InputItemsCount].ItemType = ASString; //0 - //even though Ascii we will keep value as Unicode to convert later - // no need for extra space here, it is added by ApplyInputs() - InputItems[InputItemsCount++].SValue.takeValueFrom(gSettings.Boot.BootArgs); - InputItems[InputItemsCount].ItemType = UNIString; //1 - InputItems[InputItemsCount++].SValue.takeValueFrom(gSettings.ACPI.DSDT.DsdtName); // 1-> 2 - InputItems[InputItemsCount].ItemType = UNIString; //2 - InputItems[InputItemsCount++].SValue = GlobalConfig.BlockKexts; - - InputItems[InputItemsCount].ItemType = RadioSwitch; //3 - Themes chooser - InputItems[InputItemsCount++].IValue = 3; - - InputItems[InputItemsCount].ItemType = BoolValue; //4 - InputItems[InputItemsCount++].BValue = GlobalConfig.DropSSDT; - InputItems[InputItemsCount].ItemType = BoolValue; //5 - InputItems[InputItemsCount++].BValue = gSettings.ACPI.SSDT.Generate.GeneratePStates; - InputItems[InputItemsCount].ItemType = BoolValue; //6 - InputItems[InputItemsCount++].BValue = gSettings.ACPI.SlpSmiEnable; - InputItems[InputItemsCount].ItemType = Decimal; //7 - InputItems[InputItemsCount++].SValue.SWPrintf("%02d", gSettings.ACPI.SSDT.PLimitDict); - InputItems[InputItemsCount].ItemType = Decimal; //8 - InputItems[InputItemsCount++].SValue.SWPrintf("%02d", gSettings.ACPI.SSDT.UnderVoltStep); - InputItems[InputItemsCount].ItemType = BoolValue; //9 - InputItems[InputItemsCount++].BValue = gSettings.ACPI.SSDT.Generate.GenerateCStates; - InputItems[InputItemsCount].ItemType = BoolValue; //10 - InputItems[InputItemsCount++].BValue = GlobalConfig.EnableC2; - InputItems[InputItemsCount].ItemType = BoolValue; //11 - InputItems[InputItemsCount++].BValue = GlobalConfig.EnableC4; - InputItems[InputItemsCount].ItemType = BoolValue; //12 - InputItems[InputItemsCount++].BValue = GlobalConfig.EnableC6; - InputItems[InputItemsCount].ItemType = BoolValue; //13 - InputItems[InputItemsCount++].BValue = gSettings.ACPI.SSDT.EnableISS; - InputItems[InputItemsCount].ItemType = Decimal; //14 - InputItems[InputItemsCount++].SValue.SWPrintf("%06d", gSettings.CPU.QPI); - InputItems[InputItemsCount].ItemType = BoolValue; //15 - InputItems[InputItemsCount++].BValue = gSettings.ACPI.PatchNMI; - InputItems[InputItemsCount].ItemType = BoolValue; //16 - InputItems[InputItemsCount++].BValue = gSettings.Graphics.PatchVBios; - InputItems[InputItemsCount].ItemType = Decimal; //17 - InputItems[InputItemsCount++].SValue.SWPrintf("0x%llX", gSettings.Smbios.gPlatformFeature); - InputItems[InputItemsCount].ItemType = Hex; //18 - InputItems[InputItemsCount++].SValue.SWPrintf("0x%hX", gSettings.SystemParameters.BacklightLevel); - InputItems[InputItemsCount].ItemType = Decimal; //19 - if (gSettings.CPU.BusSpeed > 20000) { - InputItems[InputItemsCount++].SValue.SWPrintf("%06d", gSettings.CPU.BusSpeed); - } else { - InputItems[InputItemsCount++].SValue.SWPrintf("%06llu", gCPUStructure.ExternalClock); - } - InputItemsCount = 20; - for (i=0; i 2 ) { //fool proof: cfg_name is 3 character or more. - InputItems[InputItemsCount++].SValue.SWPrintf("%ls", gSettings.Graphics.FBName.wc_str()); - } else { - InputItems[InputItemsCount++].SValue.SWPrintf("%s", gConf.GfxPropertiesArray[i].Config.c_str()); - } - } else if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - InputItems[InputItemsCount].ItemType = BoolValue; //21+i*6 - InputItems[InputItemsCount++].BValue = gSettings.Graphics.InjectAsDict.InjectNVidia; - InputItems[InputItemsCount].ItemType = ASString; //22+6i - for (j=0; j<8; j++) { - snprintf((CHAR8*)&tmp[2*j], 3, "%02hhX", gSettings.Graphics.Dcfg[j]); - } - InputItems[InputItemsCount++].SValue.SWPrintf("%s", tmp); - } else /*if (gGraphics[i].Vendor == Intel) */ { - InputItems[InputItemsCount].ItemType = BoolValue; //21+i*6 - InputItems[InputItemsCount++].BValue = gSettings.Graphics.InjectAsDict.InjectIntel; - InputItems[InputItemsCount].ItemType = Hex; //22+6i - InputItems[InputItemsCount++].SValue.SWPrintf("0x%08X", GlobalConfig.IgPlatform); - } - - InputItems[InputItemsCount].ItemType = Decimal; //23+6i - if (gSettings.Graphics.VideoPorts > 0) { - InputItems[InputItemsCount++].SValue.SWPrintf("%02d", gSettings.Graphics.VideoPorts); - } else { - InputItems[InputItemsCount++].SValue.SWPrintf("%02d", gConf.GfxPropertiesArray[i].Ports); - } - - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - InputItems[InputItemsCount].ItemType = ASString; //24+6i - for (j=0; j MemMap; + UINTN MemMapSize; + UINTN MapKey, DescriptorSize; + UINT32 DescriptorVersion; + EFI_STATUS Status; + + MemMapSize = 0; + DescriptorSize = 0; + Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, &DescriptorVersion); + if (Status != EFI_BUFFER_TOO_SMALL) { + DBG("PrintMemoryMap: GetMemStatus=%s not EFI_BUFFER_TOO_SMALL\n", efiStrError(Status)); + return; + } + MemMapSize += EFI_PAGE_SIZE; + MemMap = (EFI_MEMORY_DESCRIPTOR*)AllocatePool(MemMapSize); + + Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, &DescriptorVersion); + if ( EFI_ERROR(Status) ) { + DBG("PrintMemoryMap: GetMemoryMap failed=%s\n", efiStrError(Status)); + return; + } + +#ifndef JIEF_DEBUG + EFI_MEMORY_DESCRIPTOR* MemMapPtr = MemMap; + + for (UINTN Index = 0; Index < MemMapSize / DescriptorSize; Index ++) { + UINT64 Bytes = LShiftU64 (MemMapPtr->NumberOfPages, 12); + DEBUG ((EFI_D_ERROR, "%llX-%llX %llX %llX %X\n", + MemMapPtr->PhysicalStart, + MemMapPtr->PhysicalStart + Bytes - 1, + MemMapPtr->NumberOfPages, + MemMapPtr->Attribute, + MemMapPtr->Type)); + MemMapPtr = (EFI_MEMORY_DESCRIPTOR *)((UINTN)MemMapPtr + DescriptorSize); } +#else + OcPrintMemoryMap(MemMapSize, MemMap, DescriptorSize); +#endif } - -void ApplyInputs(void) +void AllocSmallBlocks(UINTN NumberOfPagesMax) { -// EFI_STATUS Status = EFI_NOT_FOUND; - MacModel Model; - XBool NeedSave = true; - INTN i = 0; - UINTN j; - -// DBG("ApplyInputs\n"); - if (InputItems[i].Valid) { - gSettings.Boot.BootArgs = InputItems[i].SValue; - gSettings.Boot.BootArgs.replaceAll('\\', '_'); - GlobalConfig.gBootChanged = true; - } - i++; //1 - if (InputItems[i].Valid) { - gSettings.ACPI.DSDT.DsdtName = InputItems[i].SValue; - } - i++; //2 - if (InputItems[i].Valid) { - GlobalConfig.BlockKexts = InputItems[i].SValue; - } - i++; //3 - if (InputItems[i].Valid) { - if (OldChosenTheme == 0xFFFF) { - gSettings.GUI.Theme = L"embedded"_XSW; - } else { - gSettings.GUI.Theme.takeValueFrom(ThemeNameArray[OldChosenTheme]); - } - - //will change theme after ESC - GlobalConfig.gThemeChanged = true; - } - i++; //4 - if (InputItems[i].Valid) { - GlobalConfig.DropSSDT = InputItems[i].BValue != 0; - } - i++; //5 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.Generate.GeneratePStates = InputItems[i].BValue != 0; - } - i++; //6 - if (InputItems[i].Valid) { - gSettings.ACPI.SlpSmiEnable = InputItems[i].BValue != 0; - } - i++; //7 - if (InputItems[i].Valid) { -// DBG("InputItems[i]: %ls\n", InputItems[i].SValue); - gSettings.ACPI.SSDT.PLimitDict = (UINT8)(StrDecimalToUintn(InputItems[i].SValue.wc_str()) & 0x7F); -// DBG("Item 7=PLimitDict %d\n", gSettings.ACPI.SSDT.PLimitDict); - } - i++; //8 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.UnderVoltStep = (UINT8)(StrDecimalToUintn(InputItems[i].SValue.wc_str()) & 0x3F); -// DBG("Item 8=UnderVoltStep %d\n", gSettings.ACPI.SSDT.UnderVoltStep); - } - i++; //9 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.Generate.GenerateCStates = InputItems[i].BValue != 0; - } - i++; //10 - if (InputItems[i].Valid) { - GlobalConfig.EnableC2 = InputItems[i].BValue != 0; - } - i++; //11 - if (InputItems[i].Valid) { - GlobalConfig.EnableC4 = InputItems[i].BValue != 0; - } - i++; //12 - if (InputItems[i].Valid) { - GlobalConfig.EnableC6 = InputItems[i].BValue != 0; - } - i++; //13 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.EnableISS = InputItems[i].BValue != 0; - } - i++; //14 - if (InputItems[i].Valid) { - gSettings.CPU.QPI = (UINT16)StrDecimalToUintn(InputItems[i].SValue.wc_str()); - DBG("applied QPI=%d\n", gSettings.CPU.QPI); - } - i++; //15 - if (InputItems[i].Valid) { - gSettings.ACPI.PatchNMI = InputItems[i].BValue != 0; - } - i++; //16 - if (InputItems[i].Valid) { - gSettings.Graphics.PatchVBios = InputItems[i].BValue != 0; - } - i++; //17 - if (InputItems[i].Valid) { - gSettings.Smbios.gPlatformFeature = (UINT64)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied PlatformFeature=0x%llX\n", gSettings.Smbios.gPlatformFeature); - } - i++; //18 | Download-Fritz: There is no GUI element for BacklightLevel; please revise - if (InputItems[i].Valid) { - gSettings.SystemParameters.BacklightLevel = (UINT16)StrHexToUint64(InputItems[i].SValue.wc_str()); - gSettings.SystemParameters.BacklightLevelConfig = true; - } - i++; //19 - if (InputItems[i].Valid) { - gSettings.CPU.BusSpeed = (UINT32)StrDecimalToUintn(InputItems[i].SValue.wc_str()); - DBG("applied BusSpeed=%d\n", gSettings.CPU.BusSpeed); - } - - i = 19; - for (j = 0; j < gConf.GfxPropertiesArrayNonConst.size(); j++) { - i++; //20 - if (InputItems[i].Valid) { - gConf.GfxPropertiesArrayNonConst[j].Model = InputItems[i].SValue; - } - i++; //21 - if (InputItems[i].Valid) { - if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Ati) { - gSettings.Graphics.InjectAsDict.InjectATI = InputItems[i].BValue != 0; - } else if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Nvidia) { - gSettings.Graphics.InjectAsDict.InjectNVidia = InputItems[i].BValue != 0; - } else if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Intel) { - gSettings.Graphics.InjectAsDict.InjectIntel = InputItems[i].BValue != 0; - } - } - i++; //22 - if (InputItems[i].Valid) { - if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Ati) { - gSettings.Graphics.FBName = InputItems[i].SValue; - } else if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Nvidia) { - hex2bin(InputItems[i].SValue, (UINT8*)&gSettings.Graphics.Dcfg[0], sizeof(gSettings.Graphics.Dcfg)); - } else if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Intel) { - //ig-platform-id for Ivy+ and snb-platform-id for Sandy - GlobalConfig.IgPlatform = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied *-platform-id=0x%X\n", GlobalConfig.IgPlatform); - } - } - - if (gConf.GfxPropertiesArrayNonConst[j].Vendor == Intel) { - i += 3; + EFI_MEMORY_DESCRIPTOR *MemMap; + UINTN MemMapSize; + UINTN MapKey, DescriptorSize; + UINT32 DescriptorVersion; + EFI_STATUS Status; + + + MemMapSize = 0; + MemMap = NULL; + DescriptorSize = 0; + Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, &DescriptorVersion); + if (Status != EFI_BUFFER_TOO_SMALL) { + DBG("PrintMemoryMap: GetMemStatus=%s not EFI_BUFFER_TOO_SMALL\n", efiStrError(Status)); + return; + } + MemMapSize += EFI_PAGE_SIZE; + MemMap = (EFI_MEMORY_DESCRIPTOR*)AllocatePool(MemMapSize); + + Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, &DescriptorVersion); + if ( EFI_ERROR(Status) ) { + DBG("PrintMemoryMap: GetMemoryMap failed=%s\n", efiStrError(Status)); + return; + } + + for ( + EFI_MEMORY_DESCRIPTOR* EntryWalker = MemMap; + (UINT8 *)EntryWalker < ((UINT8 *)MemMap + MemMapSize); + EntryWalker = NEXT_MEMORY_DESCRIPTOR (EntryWalker, DescriptorSize)) + { + if (EntryWalker->Type != EfiConventionalMemory) { continue; } - i++; //23 - if (InputItems[i].Valid) { - gConf.GfxPropertiesArrayNonConst[j].Ports = (UINT8)(StrDecimalToUintn(InputItems[i].SValue.wc_str()) & 0x0F); - } - i++; //24 - if (InputItems[i].Valid) { - if (gConf.GfxPropertiesArray[j].Vendor == Nvidia) { - if ( InputItems[i].SValue.notEmpty() ) { - hex2bin(InputItems[i].SValue, gSettings.Graphics.NVCAP.data(), gSettings.Graphics.NVCAP.size()); - } - } else { - gConf.GfxPropertiesArrayNonConst[j].Connectors = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - gConf.GfxPropertiesArrayNonConst[j].ConnChanged = true; - } - } - i++; //25 - if (InputItems[i].Valid) { - gConf.GfxPropertiesArrayNonConst[j].LoadVBios = InputItems[i].BValue != 0; + if ( (UINTN)EntryWalker->NumberOfPages < NumberOfPagesMax ) + { + gBS->AllocatePages(AllocateAddress, EfiBootServicesData, EntryWalker->NumberOfPages, &EntryWalker->PhysicalStart); } - } //end of Graphics Cards - // next number == 42 - - i = 44; - if (InputItems[i].Valid) { - GlobalConfig.KextPatchesAllowed = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //45 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.EightApple = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //46 - if (InputItems[i].Valid) { - GlobalConfig.KPAppleIntelCPUPM = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //47 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPAppleRTC = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //48 - if (InputItems[i].Valid) { - GlobalConfig.KPKernelPm = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //49 - if (InputItems[i].Valid) { - gSettings.ACPI.FixMCFG = InputItems[i].BValue != 0; - } - - i++; //50 - if (InputItems[i].Valid) { - gSettings.Graphics.RefCLK = (UINT32)StrDecimalToUintn(InputItems[i].SValue.wc_str()); } - i++; //51 - if (InputItems[i].Valid) { - NonDetected = InputItems[i].SValue; - } + FreePool(MemMap); +} - i++; //52 - if (InputItems[i].Valid) { - gSettings.Graphics.EDID.InjectEDID = InputItems[i].BValue != 0; - } - i++; //53 - if (InputItems[i].Valid) { - gSettings.Graphics.EDID.VendorEDID = (UINT16)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //54 - if (InputItems[i].Valid) { - gSettings.Graphics.EDID.ProductEDID = (UINT16)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //55 - // ErmaC: NvidiaGeneric XBool(Y/N) - if (InputItems[i].Valid) { - gSettings.Graphics.NvidiaGeneric = InputItems[i].BValue != 0; - } - i++; //56 - if (InputItems[i].Valid) { - gSettings.SystemParameters.NvidiaWeb = InputItems[i].BValue != 0; - } - i++; //57 - if (InputItems[i].Valid) { - gSettings.Devices.Audio.ResetHDA = InputItems[i].BValue != 0; - } - i++; //58 - if (InputItems[i].Valid) { - gSettings.Devices.Audio.AFGLowPowerState = InputItems[i].BValue != 0; - } - i++; //59 - if (InputItems[i].Valid) { - gSettings.Devices.Audio.HDAInjection = InputItems[i].BValue != 0; - } - i++; //60 - if (InputItems[i].Valid) { - gSettings.Devices.Audio.HDALayoutId = (UINT32)(StrDecimalToUintn(InputItems[i].SValue.wc_str())); - } - i++; //61 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPDELLSMBIOS = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //62 - if (InputItems[i].Valid) { - gSettings.Smbios.FirmwareFeatures = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied FirmwareFeatures=0x%X\n", gSettings.Smbios.FirmwareFeatures); - } - i++; //63 - if (InputItems[i].Valid) { - gSettings.Smbios.FirmwareFeaturesMask = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied FirmwareFeaturesMask=0x%X\n", gSettings.Smbios.FirmwareFeaturesMask); - } - i++; //64 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPDebug = InputItems[i].BValue != 0; - // GlobalConfig.gBootChanged = true; - } +void AllocSmallBlocks() +{ + CONST EFI_MEMORY_ATTRIBUTES_TABLE *MemoryAttributesTable; - i++; //65 - if (InputItems[i].Valid) { - XStringW& tmpStr = SmbiosList[OldChosenSmbios]; - gConf.ReloadSmbios(tmpStr); -// gConf.FillSmbiosWithDefaultValue(GlobalConfig.CurrentModel, configPlist.getSMBIOS()); +//PrintMemoryMap(); - DBG("chosen SMBIOS of %ls\n", tmpStr.wc_str()); - GlobalConfig.gBootChanged = true; - FillInputs(false); - NeedSave = false; - } - // CSR - i++; //66 - if (InputItems[i].Valid) { - gSettings.RtVariables.CsrActiveConfig = InputItems[i].IValue; - } + UINTN size = 64; + UINTN nb = 0; - i++; //67 - if (InputItems[i].Valid) { - gSettings.ACPI.DSDT.FixDsdt = InputItems[i].IValue; - } - i++; //68 - if (InputItems[i].Valid) { - GlobalConfig.OptionsBits = InputItems[i].IValue; - } - i++; //69 - if (InputItems[i].Valid) { - GlobalConfig.FlagsBits = InputItems[i].IValue; - } + AllocSmallBlocks(size); // 252KB + MemoryAttributesTable = OcGetMemoryAttributes (NULL); + nb = MemoryAttributesTable->NumberOfEntries; - i++; //70 - if (InputItems[i].Valid) { - INTN Minus = 0; - if (InputItems[i].SValue[0] == '-') { - Minus = 1; - } - gSettings.GUI.Mouse.PointerSpeed = StrDecimalToUintn(InputItems[i].SValue.data(Minus)); - if (Minus) { - gSettings.GUI.Mouse.PointerSpeed = -gSettings.GUI.Mouse.PointerSpeed; - } -// DBG("Pointer Speed=%d\n", gSettings.PointerSpeed); +//PrintMemoryMap(); + while ( size <= 2048 && nb > 100 ) { // XNU seems to handle max 128 entries. So let's shrink a little bit under 128 + size *= 2; + AllocSmallBlocks(size); + MemoryAttributesTable = OcGetMemoryAttributes (NULL); + nb = MemoryAttributesTable->NumberOfEntries; +//PrintMemoryMap(); } - i++; //71 - if (InputItems[i].Valid) { - gSettings.GUI.Mouse.DoubleClickTime = StrDecimalToUintn(InputItems[i].SValue.wc_str()); -// DBG("DoubleClickTime=%d ms\n", gSettings.DoubleClickTime); - } - i++; //72 - if (InputItems[i].Valid) { - gSettings.GUI.Mouse.PointerMirror = InputItems[i].BValue != 0; + if ( size > 2048 ) { + DBG("Cannot shrink memory map enough. Nb entries = %lld\n", nb); } +} +OC_GLOBAL_CONFIG + mOpenCoreConfiguration; - i = 74; - if (InputItems[i].Valid) { - gSettings.Devices.USB.USBFixOwnership = InputItems[i].BValue != 0; - } - i++; //75 - if (InputItems[i].Valid) { - GlobalConfig.C3Latency = (UINT16)StrHexToUint64(InputItems[i].SValue.wc_str()); - } +OC_STORAGE_CONTEXT + mOpenCoreStorage; - i++; //76 - if (InputItems[i].Valid) { - GlobalConfig.EnabledCores = (UINT8)StrDecimalToUintn(InputItems[i].SValue.wc_str()); - } - i++; //77 - if (InputItems[i].Valid) { - gSettings.CPU.SavingMode = (UINT8)StrDecimalToUintn(InputItems[i].SValue.wc_str()); - } +OC_CPU_INFO + mOpenCoreCpuInfo; - i++; //78 - if (InputItems[i].Valid) { - gSettings.Smbios.ProductName = InputItems[i].SValue; - // let's fill all other fields based on this ProductName - // to serve as default - Model = GetModelFromString(gSettings.Smbios.ProductName); - if (Model != MaxMacModel) { - GlobalConfig.CurrentModel = Model; - SetDMISettingsForModel(Model, &gSettings); - FillInputs(false); - } - } +UINT8 + mOpenCoreBooterHash[SHA1_DIGEST_SIZE]; - i++; //79 - if (InputItems[i].Valid) { - gSettings.Smbios.SystemVersion = InputItems[i].SValue; - } - i++; //80 - if (InputItems[i].Valid) { - gSettings.Smbios.SerialNr = InputItems[i].SValue; - } - i++; //81 - if (InputItems[i].Valid) { - gSettings.Smbios.BoardNumber = InputItems[i].SValue; - } - i++; //82 - if (InputItems[i].Valid) { - gSettings.Smbios.BoardSerialNumber = InputItems[i].SValue; - } - i++; //83 - if (InputItems[i].Valid) { - gSettings.Smbios.BoardType = (UINT8)(StrDecimalToUintn(InputItems[i].SValue.wc_str()) & 0x0F); - } - i++; //84 - if (InputItems[i].Valid) { - gSettings.Smbios.BoardVersion = InputItems[i].SValue; - } - i++; //85 - if (InputItems[i].Valid) { - gSettings.Smbios.ChassisType = (UINT8)(StrDecimalToUintn(InputItems[i].SValue.wc_str()) & 0x0F); - } - i++; //86 - if (InputItems[i].Valid) { - gSettings.Smbios.BiosVersion = InputItems[i].SValue; - } - i++; //87 - if (InputItems[i].Valid) { - gSettings.Smbios.BiosReleaseDate = InputItems[i].SValue; - } +OC_RSA_PUBLIC_KEY * + mOpenCoreVaultKey; - i++; //88 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.DoubleFirstState = InputItems[i].BValue != 0; - } - i++; //89 - if (InputItems[i].Valid) { - gSettings.ACPI.SSDT.EnableC7 = InputItems[i].BValue != 0; - } +OC_PRIVILEGE_CONTEXT + mOpenCorePrivilege; - i++; //90 - if (InputItems[i].Valid) { - gConf.ReLoadConfig(XStringW(ConfigsList[OldChosenConfig])); - // TODO: make a ReloadConfig, because in case of a reload, there are probably slightly different things to do. - GlobalConfig.gBootChanged = true; - GlobalConfig.gThemeChanged = true; - FillInputs(false); - NeedSave = false; - } - i++; //91 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPKernelLapic = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //92 - if (InputItems[i].Valid) { - gSettings.Devices.USB.USBInjection = InputItems[i].BValue != 0; - } - i++; //93 - if (InputItems[i].Valid) { - gSettings.Devices.USB.InjectClockID = InputItems[i].BValue != 0; - } - i++; //94 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeATI = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //95 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeNVidia = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //96 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeIntel = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied FakeIntel=0x%X\n", gSettings.Devices.FakeID.FakeIntel); - } - i++; //97 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeLAN = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //98 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeWIFI = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //99 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeSATA = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } - i++; //100 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeXHCI = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } +EFI_HANDLE + mStorageHandle; - i++; //101 - Quirks - if (InputItems[i].Valid) { - gSettings.Quirks.QuirksMask = InputItems[i].IValue; - gSettings.Quirks.OcBooterQuirks.AvoidRuntimeDefrag = ((gSettings.Quirks.QuirksMask & QUIRK_DEFRAG) != 0); //1 - gSettings.Quirks.OcBooterQuirks.DevirtualiseMmio = ((gSettings.Quirks.QuirksMask & QUIRK_MMIO) != 0); //0 - gSettings.Quirks.OcBooterQuirks.DisableSingleUser = ((gSettings.Quirks.QuirksMask & QUIRK_SU) != 0); //0 - gSettings.Quirks.OcBooterQuirks.DisableVariableWrite = ((gSettings.Quirks.QuirksMask & QUIRK_VAR) != 0); //0 - gSettings.Quirks.OcBooterQuirks.DiscardHibernateMap = ((gSettings.Quirks.QuirksMask & QUIRK_HIBER) != 0); //0 - gSettings.Quirks.OcBooterQuirks.EnableSafeModeSlide = ((gSettings.Quirks.QuirksMask & QUIRK_SAFE) != 0); //0 - gSettings.Quirks.OcBooterQuirks.EnableWriteUnprotector = ((gSettings.Quirks.QuirksMask & QUIRK_UNPROT) != 0); //1 - gSettings.Quirks.OcBooterQuirks.ForceExitBootServices = ((gSettings.Quirks.QuirksMask & QUIRK_EXIT) != 0); //0 - gSettings.Quirks.OcBooterQuirks.ProtectMemoryRegions = ((gSettings.Quirks.QuirksMask & QUIRK_REGION) != 0); //0 - gSettings.Quirks.OcBooterQuirks.ProtectSecureBoot = ((gSettings.Quirks.QuirksMask & QUIRK_SECURE) != 0); //0 - gSettings.Quirks.OcBooterQuirks.ProtectUefiServices = ((gSettings.Quirks.QuirksMask & QUIRK_UEFI) != 0); //0 - gSettings.Quirks.OcBooterQuirks.ProvideCustomSlide = ((gSettings.Quirks.QuirksMask & QUIRK_CUSTOM) != 0); //1 - gSettings.Quirks.OcBooterQuirks.RebuildAppleMemoryMap = ((gSettings.Quirks.QuirksMask & QUIRK_MAP) != 0); //0 - gSettings.Quirks.OcBooterQuirks.SetupVirtualMap = ((gSettings.Quirks.QuirksMask & QUIRK_VIRT) != 0); //1 - gSettings.Quirks.OcBooterQuirks.SignalAppleOS = ((gSettings.Quirks.QuirksMask & QUIRK_OS) != 0); //0 - gSettings.Quirks.OcBooterQuirks.SyncRuntimePermissions = ((gSettings.Quirks.QuirksMask & QUIRK_PERM) != 0); //1 - DBG("applied Quirks mask:%x\n", gSettings.Quirks.QuirksMask); //default is 0xA861 - } - i++; //102 - if (InputItems[i].Valid) { - gSettings.ACPI.DSDT.DebugDSDT = InputItems[i].BValue != 0; - } - i++; //103 - if (InputItems[i].Valid) { - gSettings.Devices.FakeID.FakeIMEI = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - } +EFI_DEVICE_PATH_PROTOCOL * + mStoragePath; - i++; //104 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.FakeCPUID = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied FakeCPUID=%06X\n", gSettings.KernelAndKextPatches.FakeCPUID); - GlobalConfig.gBootChanged = true; - } +CHAR16 * + mStorageRoot; - i++; //105 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPKernelXCPM = InputItems[i].BValue != 0; - DBG("applied KernelXCPM\n"); - GlobalConfig.gBootChanged = true; - } - - i++; //106 - if (InputItems[i].Valid) { - gSettings.Devices.StringInjector = InputItems[i].BValue != 0; - } - - i++; //107 - if (InputItems[i].Valid) { - gSettings.Devices.NoDefaultProperties = InputItems[i].BValue != 0; +VOID +OcMain ( + IN OC_STORAGE_CONTEXT *Storage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadPath + ) +{ + EFI_STATUS Status; +// OC_PRIVILEGE_CONTEXT *Privilege; + + DEBUG ((DEBUG_INFO, "OC: OcMiscEarlyInit...\n")); + Status = OcMiscEarlyInit ( + Storage, + &mOpenCoreConfiguration, + mOpenCoreVaultKey + ); + + if (EFI_ERROR (Status)) { + return; + } + +// OcCpuScanProcessor (&mOpenCoreCpuInfo); + +// DEBUG ((DEBUG_INFO, "OC: OcLoadNvramSupport...\n")); +// OcLoadNvramSupport (Storage, &mOpenCoreConfiguration); + DEBUG ((DEBUG_INFO, "OC: OcMiscMiddleInit...\n")); + OcMiscMiddleInit ( + Storage, + &mOpenCoreConfiguration, + mStorageRoot, + LoadPath, + mStorageHandle, + mOpenCoreConfiguration.Booter.Quirks.ForceBooterSignature ? mOpenCoreBooterHash : NULL + ); + DEBUG ((DEBUG_INFO, "OC: OcLoadUefiSupport...\n")); + OcLoadUefiSupport (Storage, &mOpenCoreConfiguration, &mOpenCoreCpuInfo, mOpenCoreBooterHash); +// DEBUG_CODE_BEGIN (); +// DEBUG ((DEBUG_INFO, "OC: OcMiscLoadSystemReport...\n")); +// OcMiscLoadSystemReport (&mOpenCoreConfiguration, mStorageHandle); +// DEBUG_CODE_END (); +// DEBUG ((DEBUG_INFO, "OC: OcLoadAcpiSupport...\n")); +// OcLoadAcpiSupport (&mOpenCoreStorage, &mOpenCoreConfiguration); +// DEBUG ((DEBUG_INFO, "OC: OcLoadPlatformSupport...\n")); +// OcLoadPlatformSupport (&mOpenCoreConfiguration, &mOpenCoreCpuInfo); +// DEBUG ((DEBUG_INFO, "OC: OcLoadDevPropsSupport...\n")); +// OcLoadDevPropsSupport (&mOpenCoreConfiguration); + DEBUG ((DEBUG_INFO, "OC: OcMiscLateInit...\n")); + OcMiscLateInit (Storage, &mOpenCoreConfiguration); + DEBUG ((DEBUG_INFO, "OC: OcLoadKernelSupport...\n")); + OcLoadKernelSupport (&mOpenCoreStorage, &mOpenCoreConfiguration, &mOpenCoreCpuInfo); + + if (mOpenCoreConfiguration.Misc.Security.EnablePassword) { + mOpenCorePrivilege.CurrentLevel = OcPrivilegeUnauthorized; + mOpenCorePrivilege.Hash = mOpenCoreConfiguration.Misc.Security.PasswordHash; + mOpenCorePrivilege.Salt = OC_BLOB_GET (&mOpenCoreConfiguration.Misc.Security.PasswordSalt); + mOpenCorePrivilege.SaltSize = mOpenCoreConfiguration.Misc.Security.PasswordSalt.Size; + +// Privilege = &mOpenCorePrivilege; + } else { +// Privilege = NULL; } - i++; //108 - if (InputItems[i].Valid) { - GlobalConfig.KernelPatchesAllowed = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } + DEBUG ((DEBUG_INFO, "OC: All green, starting boot management...\n")); - i++; //109 - if (InputItems[i].Valid) { - gSettings.Graphics.DualLink = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied DualLink=%X\n", gSettings.Graphics.DualLink); - } +// OcMiscBoot ( +// &mOpenCoreStorage, +// &mOpenCoreConfiguration, +// Privilege, +// OcStartImage, +// mOpenCoreConfiguration.Uefi.Quirks.RequestBootVarRouting, +// mStorageHandle +// ); +} - i++; //110 - if (InputItems[i].Valid) { - gSettings.Graphics.NvidiaNoEFI = InputItems[i].BValue != 0; - } - i++; //111 - if (InputItems[i].Valid) { - gSettings.Graphics.NvidiaSingle = InputItems[i].BValue != 0; - } - i++; //112 - if (InputItems[i].Valid) { - gSettings.Devices.IntelMaxValue = (UINT16)StrHexToUint64(InputItems[i].SValue.wc_str()); +static EFI_STATUS LoadEFIImageList(IN EFI_DEVICE_PATH **DevicePaths, + IN CONST XStringW& ImageTitle, + OUT UINTN *ErrorInStep, + OUT EFI_HANDLE *NewImageHandle) +{ + EFI_STATUS Status, ReturnStatus; + EFI_HANDLE ChildImageHandle = 0; + UINTN DevicePathIndex; + + DBG("Loading %ls", ImageTitle.wc_str()); + if (ErrorInStep != NULL) { + *ErrorInStep = 0; } - i++; //113 - if (InputItems[i].Valid) { - gSettings.ACPI.AutoMerge = InputItems[i].BValue != 0; + if (NewImageHandle != NULL) { + *NewImageHandle = NULL; } - i++; //114 - if (InputItems[i].Valid) { - gSettings.Graphics.RadeonDeInit = InputItems[i].BValue != 0; + + // load the image into memory + ReturnStatus = Status = EFI_NOT_FOUND; // in case the list is empty + for (DevicePathIndex = 0; DevicePaths[DevicePathIndex] != NULL; DevicePathIndex++) { + ReturnStatus = Status = gBS->LoadImage(false, self.getSelfImageHandle(), DevicePaths[DevicePathIndex], NULL, 0, &ChildImageHandle); + DBG(" status=%s", efiStrError(Status)); + if (ReturnStatus != EFI_NOT_FOUND) + break; } - i++; //115 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.BlockSkywalk = InputItems[i].BValue != 0; + XStringW ErrorInfo = SWPrintf(" while loading %ls", ImageTitle.wc_str()); + if (CheckError(Status, ErrorInfo.wc_str())) { + if (ErrorInStep != NULL) + *ErrorInStep = 1; + PauseForKey(NullXString8); + goto bailout; + }else{ + DBG("\n"); +#ifdef JIEF_DEBUG + DBG("ChildImaheHandle=%llx\n", uintptr_t(ChildImageHandle)); +#endif } - i++; //116 - if (InputItems[i].Valid) { - if (OldChosenDsdt == 0xFFFF) { - gSettings.ACPI.DSDT.DsdtName = L"BIOS.aml"_XSW; - } else { - gSettings.ACPI.DSDT.DsdtName = DsdtsList[OldChosenDsdt]; - } - } - i++; //117 - if (InputItems[i].Valid) { - gSettings.Smbios.EfiVersion = InputItems[i].SValue; - } - i++; //118 - if (InputItems[i].Valid) { - gSettings.RtVariables.BooterCfgStr = InputItems[i].SValue; - } - i++; //119 - if (InputItems[i].Valid) { - EFI_DEVICE_PATH_PROTOCOL* DevicePath = NULL; - int TmpIndex; - if (OldChosenAudio >= AudioList.size()) { -// DBG("crasy OldChosenAudio = %lld\n", OldChosenAudio); - OldChosenAudio = 0; - } - TmpIndex = OldChosenAudio & 0x2F; -// DBG("Chosen output %u:%ls_%s\n", TmpIndex, AudioList[TmpIndex].Name, -// AudioOutputNames[AudioList[TmpIndex].Device]); - - DevicePath = DevicePathFromHandle(AudioList[TmpIndex].Handle); -// DBG("choosen sound devicepath=%ls\n", DevicePathToStr(DevicePath)); - if (DevicePath != NULL) { - SetNvramVariable(L"Clover.SoundDevice", gEfiAppleBootGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, - GetDevicePathSize(DevicePath), (UINT8 *)DevicePath); - SetNvramVariable(L"Clover.SoundIndex", gEfiAppleBootGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, - 1, (UINT8 *)&TmpIndex); -// DBG(" sound written to nvram variables\n"); - } - } - i++; //120 - if (InputItems[i].Valid) { - DefaultAudioVolume = (UINT8)StrDecimalToUintn(InputItems[i].SValue.wc_str()); -// DBG(" set output volume to %d\n", DefaultAudioVolume); - if (DefaultAudioVolume > 100) { - // correct wrong input - DefaultAudioVolume = 90; - InputItems[i].SValue.SWPrintf("%04d", DefaultAudioVolume); - } - SetNvramVariable(L"Clover.SoundVolume", gEfiAppleBootGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, - 1, &DefaultAudioVolume); - } - i++; //121 - if (InputItems[i].Valid) { - gSettings.KernelAndKextPatches.KPPanicNoKextDump = InputItems[i].BValue != 0; - GlobalConfig.gBootChanged = true; - } - i++; //122 - if (InputItems[i].Valid) { - gSettings.Quirks.OcBooterQuirks.ProvideMaxSlide = (uint8_t)StrDecimalToUintn(InputItems[i].SValue.wc_str()); - DBG(" set MaxSlide = %hhu\n", gSettings.Quirks.OcBooterQuirks.ProvideMaxSlide); - } - i++; //123 - if (InputItems[i].Valid) { - gSettings.GUI.ProvideConsoleGop = InputItems[i].BValue != 0; - DBG("applied ConsoleGopEnable=%s\n", gSettings.GUI.ProvideConsoleGop ? "Y" : "N" ); - } - i++; //124 - if (InputItems[i].Valid) { - gSettings.ACPI.FixHeaders = InputItems[i].BValue != 0; - DBG("applied gSettings.ACPI.FixHeaders=%s\n", gSettings.ACPI.FixHeaders ? "Y" : "N" ); - } - i++; //125 - if (InputItems[i].Valid) { - gSettings.Smbios.ExtendedFirmwareFeatures = StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied ExtendedFirmwareFeatures=0x%llX\n", gSettings.Smbios.ExtendedFirmwareFeatures); - } - i++; //126 - if (InputItems[i].Valid) { - gSettings.Smbios.ExtendedFirmwareFeaturesMask = StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("applied ExtendedFirmwareFeaturesMask=0x%llX\n", gSettings.Smbios.ExtendedFirmwareFeaturesMask); - } - i++; //127 - if (InputItems[i].Valid) { - INTN Minus = 0; - if (InputItems[i].SValue[0] == '-') { - Minus = 1; - } - gSettings.Quirks.OcBooterQuirks.ResizeAppleGpuBars = StrDecimalToUintn(InputItems[i].SValue.data(Minus)); - if (Minus) { - gSettings.Quirks.OcBooterQuirks.ResizeAppleGpuBars = -gSettings.Quirks.OcBooterQuirks.ResizeAppleGpuBars; - } - DBG(" set GpuBar = %d\n", gSettings.Quirks.OcBooterQuirks.ResizeAppleGpuBars); - } - i++; //128 - if (InputItems[i].Valid) { - gSettings.Quirks.OcKernelQuirks.ProvideCurrentCpuInfo = InputItems[i].BValue != 0; - DBG("applied ProvideCurrentCpuInfo=%s\n", gSettings.Quirks.OcKernelQuirks.ProvideCurrentCpuInfo ? "Y" : "N" ); - } - i++; //129 - if (InputItems[i].Valid) { - gResetSMC = InputItems[i].BValue != 0; - if (gResetSMC) { - // reset controller - if (gAppleSmc && (gAppleSmc->Signature == NON_APPLE_SMC_SIGNATURE)) { - gAppleSmc->SmcReset(gAppleSmc, 1); - DBG("SMC store is resetted\n"); - } else { - DBG("SMC protocol not found\n"); - } - gResetSMC = false; + + if (!EFI_ERROR(ReturnStatus)) { //why unload driver?! + if (NewImageHandle != NULL) { + *NewImageHandle = ChildImageHandle; } - } - i++; //130 - if (InputItems[i].Valid) { - INTN Minus = 0; - gSettings.Quirks.OcBooterQuirks.TscSyncTimeout = (decltype(gSettings.Quirks.OcBooterQuirks.TscSyncTimeout))StrDecimalToUintn(InputItems[i].SValue.data(Minus)); - DBG("set TscSyncTimeout=%d\n", gSettings.Quirks.OcBooterQuirks.TscSyncTimeout); - } - //gSettings.Smbios.SFakeCPU - i++; //131 - if (InputItems[i].Valid) { - gSettings.Smbios.SFakeCPU = (UINT32)StrHexToUint64(InputItems[i].SValue.wc_str()); - DBG("set FakeCPUID=%X\n", gSettings.Smbios.SFakeCPU); +#ifdef JIEF_DEBUG + EFI_LOADED_IMAGE_PROTOCOL* loadedBootImage = NULL; + if (!EFI_ERROR(Status = gBS->HandleProtocol(ChildImageHandle, &gEfiLoadedImageProtocolGuid, (void**)(&loadedBootImage)))) { + DBG("%ls : Image base = 0x%llx\n", ImageTitle.wc_str(), (uintptr_t)loadedBootImage->ImageBase); // Jief : Do not change this, it's used by grep to feed the debugger + }else{ + DBG("Can't get loaded image protocol\n"); + } +#endif + goto bailout; } - if (NeedSave) { - ApplySettings(); - } + // unload the image, we don't care if it works or not... + Status = gBS->UnloadImage(ChildImageHandle); +bailout: + return ReturnStatus; } -void AboutRefit(void) +static EFI_STATUS StartEFILoadedImage(IN EFI_HANDLE ChildImageHandle, + IN CONST XString8Array& LoadOptions, IN CONST XStringW& LoadOptionsPrefix, + IN CONST XStringW& ImageTitle, + OUT UINTN *ErrorInStep) { - if (AboutMenu.Entries.size() == 0) { - AboutMenu.Daylight = ThemeX->Daylight; - if (!(ThemeX->HideUIFlags & HIDEUI_FLAG_MENU_TITLE_IMAGE)) { - AboutMenu.TitleImage = ThemeX->GetIcon(BUILTIN_ICON_FUNC_ABOUT); - } - - if ( "unknown"_XS8 != LString8(gRevisionStr) ) AboutMenu.AddMenuInfo_f("%s", gRevisionStr); - if ( "unknown"_XS8 != LString8(gFirmwareBuildDate) ) AboutMenu.AddMenuInfo_f(" Build: %s", gFirmwareBuildDate); - if ( "unknown"_XS8 != gBuildId ) AboutMenu.AddMenuInfo_f(" Build id: %s", gBuildId.c_str()); - AboutMenu.AddMenuInfo_f("%s", path_independant.c_str()); // trick to let the compiler think path_independant is used and must be kept in binary. - AboutMenu.Entries[AboutMenu.Entries.size()-1].Title.SWPrintf("%s", gBuildIdGrepTag.c_str()); - AboutMenu.Entries[AboutMenu.Entries.size()-1].Title.SWPrintf(" "); - AboutMenu.AddMenuInfo_f("Based on rEFIt (c) 2006-2010 Christoph Pfisterer"); - AboutMenu.AddMenuInfo_f("Portions Copyright (c) Intel Corporation"); - AboutMenu.AddMenuInfo_f("Developers:"); - AboutMenu.AddMenuInfo_f(" Slice, dmazar, apianti, JrCs, pene, usrsse2"); - AboutMenu.AddMenuInfo_f(" Kabyl, pcj, jadran, Blackosx, STLVNUB, ycr.ru"); - AboutMenu.AddMenuInfo_f(" FrodoKenny, skoczi, crazybirdy, Oscar09, xsmile"); - AboutMenu.AddMenuInfo_f(" cparm, rehabman, nms42, Sherlocks, Zenith432"); - AboutMenu.AddMenuInfo_f(" stinga11, TheRacerMaster, solstice, SoThOr, DF"); - AboutMenu.AddMenuInfo_f(" cecekpawon, Micky1979, Needy, joevt, ErmaC, vit9696"); - AboutMenu.AddMenuInfo_f(" ath, savvas, syscl, goodwin_c, clovy, jief_machak"); - AboutMenu.AddMenuInfo_f(" chris1111, vector_sigma, LAbyOne, Florin9doi"); - AboutMenu.AddMenuInfo_f("Package credits:"); - AboutMenu.AddMenuInfo_f(" Chameleon team, crazybirdy, JrCs, chris1111"); - AboutMenu.AddMenuInfo_f("Credits also:"); - AboutMenu.AddMenuInfo_f(" projectosx.com, applelife.ru, insanelymac.com"); - AboutMenu.AddMenuInfo_f(" "); - AboutMenu.AddMenuInfo_f("Running on:"); - AboutMenu.AddMenuInfo_f(" EFI Revision %d.%02d", - gST->Hdr.Revision >> 16, gST->Hdr.Revision & ((1 << 16) - 1)); -#if defined(MDE_CPU_IA32) - AboutMenu.AddMenuInfo_f(" Platform: i386 (32 bit)"); -#elif defined(MDE_CPU_X64) - AboutMenu.AddMenuInfo_f(" Platform: x86_64 (64 bit)"); -#elif defined(_MSC_VER) - AboutMenu.AddMenuInfo_f(" Platform: x86_64 (64 bit) VS"); -#else - AboutMenu.AddMenuInfo_f(" Platform: unknown"); -#endif - AboutMenu.AddMenuInfo_f(" Firmware: %ls rev %d.%04d", gST->FirmwareVendor, gST->FirmwareRevision >> 16, gST->FirmwareRevision & ((1 << 16) - 1)); - AboutMenu.AddMenuInfo_f(" Screen Output: %s", egScreenDescription().c_str()); - AboutMenu.GetAnime(); - AboutMenu.AddMenuEntry(&MenuEntryReturn, false); - } else if (AboutMenu.Entries.size() >= 2) { - AboutMenu.Entries[AboutMenu.Entries.size()-2].Title.SWPrintf(" Screen Output: %s", egScreenDescription().c_str()); - } + EFI_STATUS Status, ReturnStatus; + EFI_LOADED_IMAGE_PROTOCOL *ChildLoadedImage; + CHAR16 ErrorInfo[256]; - AboutMenu.RunMenu(NULL); -} + XStringW loadOptionsW; // This has to be declared here, so it's not be freed before calling StartImage -void HelpRefit(void) -{ - if (HelpMenu.Entries.size() == 0) { - HelpMenu.Daylight = ThemeX->Daylight; - if (!(ThemeX->HideUIFlags & HIDEUI_FLAG_MENU_TITLE_IMAGE)) { - HelpMenu.TitleImage = ThemeX->GetIcon(BUILTIN_ICON_FUNC_HELP); +// DBG("Starting %ls\n", ImageTitle); + if (ErrorInStep != NULL) { + *ErrorInStep = 0; + } + ReturnStatus = Status = EFI_NOT_FOUND; // in case no image handle was specified + if (ChildImageHandle == NULL) { + if (ErrorInStep != NULL) *ErrorInStep = 1; + goto bailout; + } + + // set load options + if (!LoadOptions.isEmpty()) { + ReturnStatus = Status = gBS->HandleProtocol(ChildImageHandle, &gEfiLoadedImageProtocolGuid, (void **) &ChildLoadedImage); + if (CheckError(Status, L"while getting a LoadedImageProtocol handle")) { + if (ErrorInStep != NULL) + *ErrorInStep = 2; + goto bailout_unload; } - switch (gSettings.GUI.languageCode) - { - case russian: - HelpMenu.AddMenuInfo_f("ESC - Выход из подменю, обновление главного меню"); - HelpMenu.AddMenuInfo_f("F1 - Помощь по горячим клавишам"); - HelpMenu.AddMenuInfo_f("F2 - Сохранить отчет в preboot.log (только если FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Показать скрытые значки в меню"); - HelpMenu.AddMenuInfo_f("F4 - Родной DSDT сохранить в %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Патченный DSDT сохранить в %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Сохранить ВидеоБиос в %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Проверить звук на выбранном выходе"); - HelpMenu.AddMenuInfo_f("F8 - Сделать дамп звуковых устройств в %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Изменить разрешение экрана на одно из возможных"); - HelpMenu.AddMenuInfo_f("F10 - Снимок экрана в папку %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Извлечь указанный DVD"); - HelpMenu.AddMenuInfo_f("Пробел - Дополнительное меню запуска выбранного тома"); - HelpMenu.AddMenuInfo_f("Цифры 1-9 - Быстрый запуск тома по порядку в меню"); - HelpMenu.AddMenuInfo_f("A (About) - О загрузчике"); - HelpMenu.AddMenuInfo_f("O (Options) - Дополнительные настройки"); - HelpMenu.AddMenuInfo_f("R (Reset) - Теплый перезапуск"); - HelpMenu.AddMenuInfo_f("U (go oUt) - Завершить работу в Кловере"); - HelpMenu.AddMenuInfo_f("S (Shell) - Переход в режим командной строки"); - break; - case ukrainian: - HelpMenu.AddMenuInfo_f("ESC - Вийти з меню, оновити головне меню"); - HelpMenu.AddMenuInfo_f("F1 - Ця довідка"); - HelpMenu.AddMenuInfo_f("F2 - Зберегти preboot.log (тiльки FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Відображати приховані розділи"); - HelpMenu.AddMenuInfo_f("F4 - Зберегти OEM DSDT в %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Зберегти патчений DSDT в %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F6 - Зберегти VideoBios в %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F10 - Зберегти знімок екрану в %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Відкрити обраний диск (DVD)"); - HelpMenu.AddMenuInfo_f("Пробіл - докладніше про обраний пункт меню"); - HelpMenu.AddMenuInfo_f("Клавіші 1-9 -  клавіші пунктів меню"); - HelpMenu.AddMenuInfo_f("A - Про систему"); - HelpMenu.AddMenuInfo_f("O - Опції меню"); - HelpMenu.AddMenuInfo_f("R - Перезавантаження"); - HelpMenu.AddMenuInfo_f("U - Відключити ПК"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case spanish: - HelpMenu.AddMenuInfo_f("ESC - Salir de submenu o actualizar el menu principal"); - HelpMenu.AddMenuInfo_f("F1 - Esta Ayuda"); - HelpMenu.AddMenuInfo_f("F2 - Guardar preboot.log (Solo FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Guardar DSDT oem en %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Guardar DSDT parcheado en %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Guardar VideoBios en %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Guardar Captura de pantalla en %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Expulsar volumen seleccionado (DVD)"); - HelpMenu.AddMenuInfo_f("Espacio - Detalles acerca selected menu entry"); - HelpMenu.AddMenuInfo_f("Digitos 1-9 - Atajo a la entrada del menu"); - HelpMenu.AddMenuInfo_f("A - Menu Acerca de"); - HelpMenu.AddMenuInfo_f("O - Menu Optiones"); - HelpMenu.AddMenuInfo_f("R - Reiniciar Equipo"); - HelpMenu.AddMenuInfo_f("U - Apagar"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case portuguese: - case brasil: - HelpMenu.AddMenuInfo_f("ESC - Sai do submenu, atualiza o menu principal"); - HelpMenu.AddMenuInfo_f("F1 - Esta ajuda"); - HelpMenu.AddMenuInfo_f("F2 - Salva preboot.log (somente FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Salva oem DSDT em %ls/ACPI/origin/ (somente FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Salva DSDT corrigido em %ls/ACPI/origin/ (somente FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Salva VideoBios em %ls/misc/ (somente FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Salva screenshot em %ls/misc/ (somente FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Ejeta o volume selecionado (DVD)"); - HelpMenu.AddMenuInfo_f("Espaco - Detalhes sobre a opcao do menu selecionada"); - HelpMenu.AddMenuInfo_f("Tecle 1-9 - Atalho para as entradas do menu"); - HelpMenu.AddMenuInfo_f("A - Sobre o Menu"); - HelpMenu.AddMenuInfo_f("O - Opcoes do Menu"); - HelpMenu.AddMenuInfo_f("R - Reiniciar"); - HelpMenu.AddMenuInfo_f("U - Desligar"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case italian: - HelpMenu.AddMenuInfo_f("ESC - Esci dal submenu, Aggiorna menu principale"); - HelpMenu.AddMenuInfo_f("F1 - Aiuto"); - HelpMenu.AddMenuInfo_f("F2 - Salva il preboot.log (solo su FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Mostra volumi nascosti"); - HelpMenu.AddMenuInfo_f("F4 - Salva il DSDT oem in %ls/ACPI/origin/ (solo suFAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Salva il patched DSDT in %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Salva il VideoBios in %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Controlla il suono sull'uscita selezionata"); - HelpMenu.AddMenuInfo_f("F8 - Scarica le uscite audio in %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Cambia la risoluzione dello schermo alla prossima disponibile"); - HelpMenu.AddMenuInfo_f("F10 - Salva screenshot in %ls/misc/ (solo su FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Resetta NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Espelli il volume selezionato (DVD)"); - HelpMenu.AddMenuInfo_f("Spazio - Dettagli sul menu selezionato"); - HelpMenu.AddMenuInfo_f("Digita 1-9 - Abbreviazioni per il menu"); - HelpMenu.AddMenuInfo_f("A - Informazioni"); - HelpMenu.AddMenuInfo_f("O - Menu Opzioni"); - HelpMenu.AddMenuInfo_f("R - Riavvio"); - HelpMenu.AddMenuInfo_f("U - Spegnimento"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case german: - HelpMenu.AddMenuInfo_f("ESC - Zurueck aus Untermenue, Hauptmenue erneuern"); - HelpMenu.AddMenuInfo_f("F1 - Diese Hilfe"); - HelpMenu.AddMenuInfo_f("F2 - Sichere preboot.log (nur mit FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Sichere OEM DSDT in %ls/ACPI/origin/ (nur mit FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Sichere gepatchtes DSDT in %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Sichere VideoBios in %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Sichere Bildschirmfoto in %ls/misc/ (nur mit FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Volume auswerfen (DVD)"); - HelpMenu.AddMenuInfo_f("Leertaste - Details über den gewählten Menue Eintrag"); - HelpMenu.AddMenuInfo_f("Zahlen 1-9 - Kurzwahl zum Menue Eintrag"); - HelpMenu.AddMenuInfo_f("A - Menue Informationen"); - HelpMenu.AddMenuInfo_f("O - Menue Optionen"); - HelpMenu.AddMenuInfo_f("R - Neustart"); - HelpMenu.AddMenuInfo_f("U - Ausschalten"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case dutch: - HelpMenu.AddMenuInfo_f("ESC - Verlaat submenu, Vernieuw hoofdmenu"); - HelpMenu.AddMenuInfo_f("F1 - Onderdeel hulp"); - HelpMenu.AddMenuInfo_f("F2 - preboot.log opslaan (Alleen FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Verborgen opties weergeven"); - HelpMenu.AddMenuInfo_f("F4 - Opslaan oem DSDT in %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Opslaan gepatchte DSDT in %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Opslaan VideoBios in %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Controleer geluid op geselecteerde uitgang"); - HelpMenu.AddMenuInfo_f("F8 - Opslaan audio uitgangen in %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Wijzig schermresolutie naar eerstvolgende mogelijke modus"); - HelpMenu.AddMenuInfo_f("F10 - Opslaan schermafdruk in %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Uitwerpen geselecteerd volume (DVD)"); - HelpMenu.AddMenuInfo_f("Spatie - Details over geselecteerd menuoptie"); - HelpMenu.AddMenuInfo_f("Cijfers 1-9 - Snelkoppeling naar menuoptie"); - HelpMenu.AddMenuInfo_f("A - Menu Over"); - HelpMenu.AddMenuInfo_f("O - Menu Opties"); - HelpMenu.AddMenuInfo_f("R - Soft Reset"); - HelpMenu.AddMenuInfo_f("U - Verlaten"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case french: - HelpMenu.AddMenuInfo_f("ESC - Quitter sous-menu, Retour menu principal"); - HelpMenu.AddMenuInfo_f("F1 - Aide"); - HelpMenu.AddMenuInfo_f("F2 - Enregistrer preboot.log (FAT32 only)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Enregistrer oem DSDT dans %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Enregistrer DSDT modifié dans %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Enregistrer VideoBios dans %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Enregistrer la capture d'écran dans %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Ejecter le volume (DVD)"); - HelpMenu.AddMenuInfo_f("Space - Détails a propos du menu selectionné"); - HelpMenu.AddMenuInfo_f("Digits 1-9 - Raccourci vers entrée menu"); - HelpMenu.AddMenuInfo_f("A - A propos"); - HelpMenu.AddMenuInfo_f("O - Options Menu"); - HelpMenu.AddMenuInfo_f("R - Redémarrer"); - HelpMenu.AddMenuInfo_f("U - Eteindre"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case indonesian: - HelpMenu.AddMenuInfo_f("ESC - Keluar submenu, Refresh main menu"); - HelpMenu.AddMenuInfo_f("F1 - Help"); - HelpMenu.AddMenuInfo_f("F2 - Simpan preboot.log ke %ls/ACPI/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Simpan oem DSDT ke %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Simpan patched DSDT ke %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Simpan VideoBios ke %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Simpan screenshot ke %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Eject volume (DVD)"); - HelpMenu.AddMenuInfo_f("Spasi - Detail dari menu yang dipilih"); - HelpMenu.AddMenuInfo_f("Tombol 1-9 - Shortcut pilihan menu"); - HelpMenu.AddMenuInfo_f("A - About"); - HelpMenu.AddMenuInfo_f("O - Opsi"); - HelpMenu.AddMenuInfo_f("R - Soft Reset"); - HelpMenu.AddMenuInfo_f("U - Shutdown"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case polish: - HelpMenu.AddMenuInfo_f("ESC - Wyjscie z podmenu, Odswiezenie glownego menu"); - HelpMenu.AddMenuInfo_f("F1 - Pomoc"); - HelpMenu.AddMenuInfo_f("F2 - Zapis preboot.log (tylko FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Zapis DSDT do %ls/ACPI/origin/ (tylko FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Zapis poprawionego DSDT do %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Zapis BIOSu k. graficznej do %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Zapis zrzutu ekranu do %ls/misc/ (tylko FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Wysuniecie zaznaczonego dysku (tylko dla DVD)"); - HelpMenu.AddMenuInfo_f("Spacja - Informacje nt. dostepnych opcji dla zaznaczonego dysku"); - HelpMenu.AddMenuInfo_f("Znaki 1-9 - Skroty opcji dla wybranego dysku"); - HelpMenu.AddMenuInfo_f("A - Menu Informacyjne"); - HelpMenu.AddMenuInfo_f("O - Menu Opcje"); - HelpMenu.AddMenuInfo_f("R - Restart komputera"); - HelpMenu.AddMenuInfo_f("U - Wylaczenie komputera"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case croatian: - HelpMenu.AddMenuInfo_f("ESC - izlaz iz podizbornika, Osvježi glavni izbornik"); - HelpMenu.AddMenuInfo_f("F1 - Ovaj izbornik"); - HelpMenu.AddMenuInfo_f("F2 - Spremi preboot.log (samo na FAT32)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Spremi oem DSDT u %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Spremi patched DSDT into %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Spremi VideoBios into %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Spremi screenshot into %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Izbaci izabrai (DVD)"); - HelpMenu.AddMenuInfo_f("Space - Detalji o odabranom sistemu"); - HelpMenu.AddMenuInfo_f("Brojevi 1 do 9 su prečac do izbora"); - HelpMenu.AddMenuInfo_f("A - Izbornik o meni"); - HelpMenu.AddMenuInfo_f("O - Izbornik opcije"); - HelpMenu.AddMenuInfo_f("R - Restart računala"); - HelpMenu.AddMenuInfo_f("U - Isključivanje računala"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case czech: - HelpMenu.AddMenuInfo_f("ESC - Vrátit se do hlavní nabídky"); - HelpMenu.AddMenuInfo_f("F1 - Tato Nápověda"); - HelpMenu.AddMenuInfo_f("F2 - Uložit preboot.log (FAT32 only)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Uložit oem DSDT do %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Uložit patchnuté DSDT do %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Uložit VideoBios do %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Uložit snímek obrazovky do %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Vysunout vybranou mechaniku (DVD)"); - HelpMenu.AddMenuInfo_f("Mezerník - Podrobnosti o vybraném disku"); - HelpMenu.AddMenuInfo_f("čísla 1-9 - Klávesové zkratky pro disky"); - HelpMenu.AddMenuInfo_f("A - Menu O Programu"); - HelpMenu.AddMenuInfo_f("O - Menu Možnosti"); - HelpMenu.AddMenuInfo_f("R - Částečný restart"); - HelpMenu.AddMenuInfo_f("U - Odejít"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case korean: - HelpMenu.AddMenuInfo_f("ESC - 하위메뉴에서 나감, 메인메뉴 새로 고침"); - HelpMenu.AddMenuInfo_f("F1 - 이 도움말"); - HelpMenu.AddMenuInfo_f("F2 - preboot.log를 저장합니다. (FAT32방식에만 해당됨)"); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - oem DSDT를 %ls/ACPI/origin/에 저장합니다. (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - 패치된 DSDT를 %ls/ACPI/origin/에 저장합니다. (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - VideoBios를 %ls/misc/에 저장합니다. (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - 선택한 출력에서 사운드 확인"); - HelpMenu.AddMenuInfo_f("F8 - 오디오 코덱덤프를 %ls/misc/에 저장합니다.", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - 스크린샷을 %ls/misc/에 저장합니다. (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - NVRAM 초기화"); - HelpMenu.AddMenuInfo_f("F12 - 선택한 볼륨을 제거합니다. (DVD)"); - HelpMenu.AddMenuInfo_f("Space - 선택한 메뉴의 상세 설명"); - HelpMenu.AddMenuInfo_f("Digits 1-9 - 메뉴 단축 번호"); - HelpMenu.AddMenuInfo_f("A - 단축키 - 이 부트로더에 관하여"); - HelpMenu.AddMenuInfo_f("O - 단축키 - 부트 옵션"); - HelpMenu.AddMenuInfo_f("R - 단축키 - 리셋"); - HelpMenu.AddMenuInfo_f("U - 단축키 - 시스템 종료"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case romanian: - HelpMenu.AddMenuInfo_f("ESC - Iesire din sub-meniu, Refresh meniul principal"); - HelpMenu.AddMenuInfo_f("F1 - Ajutor"); - HelpMenu.AddMenuInfo_f("F2 - Salvare preboot.log (doar pentru FAT32)"); - HelpMenu.AddMenuInfo_f("F4 - Salvare oem DSDT in EFI/ACPI/origin/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F5 - Salvare DSDT modificat in EFI/ACPI/origin/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F6 - Salvare VideoBios in EFI/misc/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resoluton to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Salvare screenshot in EFI/misc/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Scoatere volum selectat (DVD)"); - HelpMenu.AddMenuInfo_f("Space - Detalii despre item-ul selectat"); - HelpMenu.AddMenuInfo_f("Cifre 1-9 - Scurtaturi pentru itemele meniului"); - HelpMenu.AddMenuInfo_f("A - Despre"); - HelpMenu.AddMenuInfo_f("O - Optiuni"); - HelpMenu.AddMenuInfo_f("R - Soft Reset"); - HelpMenu.AddMenuInfo_f("U - Inchidere"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case chinese: - HelpMenu.AddMenuInfo_f("ESC - 离开子菜单, 刷新主菜单"); - HelpMenu.AddMenuInfo_f("F1 - 帮助"); - HelpMenu.AddMenuInfo_f("F2 - 保存 preboot.log 到 %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F3 - 显示隐藏的启动项"); - HelpMenu.AddMenuInfo_f("F4 - 保存原始的 DSDT 到 EFI/ACPI/origin/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F5 - 保存修正后的 DSDT 到 EFI/ACPI/origin/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F6 - 保存 VideoBios 到 EFI/misc/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F7 - 检查选中输出设备的声音"); - HelpMenu.AddMenuInfo_f("F8 - 生成声卡输出转储到 %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - 调整屏幕分辨率为下一个可用的模式"); - HelpMenu.AddMenuInfo_f("F10 - 保存截图到 EFI/misc/ (FAT32)"); - HelpMenu.AddMenuInfo_f("F11 - 重置 NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - 推出选中的卷 (DVD)"); - HelpMenu.AddMenuInfo_f("空格 - 关于选中项的详情"); - HelpMenu.AddMenuInfo_f("数字 1-9 - 菜单快捷键"); - HelpMenu.AddMenuInfo_f("A - 关于"); - HelpMenu.AddMenuInfo_f("O - 选项"); - HelpMenu.AddMenuInfo_f("R - 软复位"); - HelpMenu.AddMenuInfo_f("U - 退出"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; - case english: - default: - HelpMenu.AddMenuInfo_f("ESC - Escape from submenu, Refresh main menu"); - HelpMenu.AddMenuInfo_f("F1 - This help"); - HelpMenu.AddMenuInfo_f("F2 - Save preboot.log into %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F3 - Show hidden entries"); - HelpMenu.AddMenuInfo_f("F4 - Save oem DSDT into %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F5 - Save patched DSDT into %ls/ACPI/origin/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F6 - Save VideoBios into %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F7 - Check sound on selected output"); - HelpMenu.AddMenuInfo_f("F8 - Make audio outputs dump into %ls/misc/", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F9 - Switch screen resolution to next possible mode"); - HelpMenu.AddMenuInfo_f("F10 - Save screenshot into %ls/misc/ (FAT32)", self.getCloverDirFullPath4Display().wc_str()); - HelpMenu.AddMenuInfo_f("F11 - Reset NVRAM"); - HelpMenu.AddMenuInfo_f("F12 - Eject selected volume (DVD)"); - HelpMenu.AddMenuInfo_f("Space - Details about selected menu entry"); - HelpMenu.AddMenuInfo_f("Digits 1-9 - Shortcut to menu entry"); - HelpMenu.AddMenuInfo_f("A - Menu About"); - HelpMenu.AddMenuInfo_f("O - Menu Options"); - HelpMenu.AddMenuInfo_f("R - Soft Reset"); - HelpMenu.AddMenuInfo_f("U - Exit from Clover"); - HelpMenu.AddMenuInfo_f("S - Shell"); - break; + + if ( LoadOptionsPrefix.notEmpty() ) { + // NOTE: That last space is also added by the EFI shell and seems to be significant + // when passing options to Apple's boot.efi... + loadOptionsW = SWPrintf("%ls %s ", LoadOptionsPrefix.wc_str(), LoadOptions.ConcatAll(" "_XS8).c_str()); + }else{ + loadOptionsW = SWPrintf("%s ", LoadOptions.ConcatAll(" "_XS8).c_str()); // Jief : should we add a space ? Wasn't the case before big refactoring. Yes, a space required. } - HelpMenu.GetAnime(); - HelpMenu.AddMenuEntry(&MenuEntryReturn, false); + // NOTE: We also include the terminating null in the length for safety. + ChildLoadedImage->LoadOptionsSize = (UINT32)loadOptionsW.sizeInBytes() + sizeof(wchar_t); + ChildLoadedImage->LoadOptions = loadOptionsW.wc_str(); //will it be deleted after the procedure exit? Yes, if we don't copy loadOptionsW, so it'll be freed at the end of method + + DBG("start image '%ls'\n", ImageTitle.s()); + DBG("Using load options '%ls'\n", (CHAR16*)ChildLoadedImage->LoadOptions); + } + + // close open file handles + UninitRefitLib(); - HelpMenu.RunMenu(NULL); -} + // turn control over to the image + // + // Before calling the image, enable the Watchdog Timer for + // the 5 Minute period - Slice - NO! For slow driver and slow disk we need more + // + gBS->SetWatchdogTimer (600, 0x0000, 0x00, NULL); -// -// Graphics helper functions -// + ReturnStatus = Status = gBS->StartImage(ChildImageHandle, NULL, NULL); + // + // Clear the Watchdog Timer after the image returns + // + gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL); -/* - SelectionImages: - [0] SelectionBig - [2] SelectionSmall - [4] SelectionIndicator - Buttons: - [0] radio_button - [1] radio_button_selected - [2] checkbox - [3] checkbox_checked -*/ + ReinitRefitLib(); + // control returns here when the child image calls Exit() + if (ImageTitle.notEmpty()) { + snwprintf(ErrorInfo, 512, "returned from %ls", ImageTitle.s()); + } -// -// user-callable dispatcher functions -// + if (CheckError(Status, ErrorInfo)) { + if (ErrorInStep != NULL) + *ErrorInStep = 3; + } + if (!EFI_ERROR(ReturnStatus)) { //why unload driver?! + goto bailout; + } -REFIT_ABSTRACT_MENU_ENTRY* NewEntry_(REFIT_ABSTRACT_MENU_ENTRY *Entry, REFIT_MENU_SCREEN **SubScreen, ACTION AtClick, UINTN ID, const XString8& Title) -{ - Entry->Title = Title; - Entry->Image = OptionMenu.TitleImage; - Entry->AtClick = AtClick; - // create the submenu - *SubScreen = new REFIT_MENU_SCREEN; - (*SubScreen)->Title = Entry->Title; - (*SubScreen)->TitleImage = Entry->Image; - (*SubScreen)->ID = ID; - (*SubScreen)->GetAnime(); - Entry->SubScreen = *SubScreen; - return Entry; +bailout_unload: + // unload the image, we don't care if it works or not... + Status = gBS->UnloadImage(ChildImageHandle); +bailout: + return ReturnStatus; } -REFIT_MENU_ITEM_OPTIONS* newREFIT_MENU_ITEM_OPTIONS(REFIT_MENU_SCREEN **SubScreen, ACTION AtClick, UINTN ID, const XString8& Title) -{ - REFIT_MENU_ITEM_OPTIONS* Entry = new REFIT_MENU_ITEM_OPTIONS; - return NewEntry_(Entry, SubScreen, AtClick, ID, Title)->getREFIT_MENU_ITEM_OPTIONS(); -} -void ModifyTitles(REFIT_ABSTRACT_MENU_ENTRY *ChosenEntry) +static EFI_STATUS LoadEFIImage(IN EFI_DEVICE_PATH *DevicePath, + IN CONST XStringW& ImageTitle, + OUT UINTN *ErrorInStep, + OUT EFI_HANDLE *NewImageHandle) { - if (ChosenEntry->SubScreen->ID == SCREEN_DSDT) { - ChosenEntry->Title.SWPrintf("DSDT fix mask [0x%08x]->", gSettings.ACPI.DSDT.FixDsdt); - //MsgLog("@ESC: %ls\n", (*ChosenEntry)->Title); - } else if (ChosenEntry->SubScreen->ID == SCREEN_CSR) { - // CSR - ChosenEntry->Title.SWPrintf("System Integrity Protection [0x%04x]->", gSettings.RtVariables.CsrActiveConfig); - // check for the right booter flag to allow the application - // of the new System Integrity Protection configuration. - if (gSettings.RtVariables.CsrActiveConfig != 0 && gSettings.RtVariables.BooterConfig == 0) { - gSettings.RtVariables.BooterConfig = 0x28; - } -// } else if (ChosenEntry->SubScreen->ID == SCREEN_BLC) { -// ChosenEntry->Title.SWPrintf("boot_args->flags [0x%04hx]->", gSettings.RtVariables.BooterConfig); + EFI_DEVICE_PATH *DevicePaths[2]; + +#ifdef ENABLE_SECURE_BOOT + // Verify secure boot policy + if (GlobalConfig.SecureBoot && GlobalConfig.SecureBootSetupMode) { + // Only verify if in forced secure boot mode + EFI_STATUS Status = VerifySecureBootImage(DevicePath); + if (EFI_ERROR(Status)) { + return Status; + } } +#endif // ENABLE_SECURE_BOOT + + // Load the image now + DevicePaths[0] = DevicePath; + DevicePaths[1] = NULL; + return LoadEFIImageList(DevicePaths, ImageTitle, ErrorInStep, NewImageHandle); } -REFIT_ABSTRACT_MENU_ENTRY *SubMenuGraphics() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_GRAPHICS, "Graphics Injector->"_XS8); - SubScreen->AddMenuInfoLine_f("Number of VideoCard%s=%zu",((gConf.GfxPropertiesArray.size()!=1)?"s":""), gConf.GfxPropertiesArray.size()); - SubScreen->AddMenuItemInput(52, "InjectEDID", false); - SubScreen->AddMenuItemInput(53, "Fake Vendor EDID:", true); - SubScreen->AddMenuItemInput(54, "Fake Product EDID:", true); - SubScreen->AddMenuItemInput(18, "Backlight Level:", true); - SubScreen->AddMenuItemInput(112, "Intel Max Backlight:", true); //gSettings.Devices.IntelMaxValue - - - for (UINTN i = 0; i < gConf.GfxPropertiesArray.size(); i++) { - SubScreen->AddMenuInfo_f("----------------------"); - SubScreen->AddMenuInfo_f("Card DeviceID=%04hx", gConf.GfxPropertiesArray[i].DeviceID); - UINTN N = 20 + i * 6; - SubScreen->AddMenuItemInput(N, "Model:", true); - - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - SubScreen->AddMenuItemInput(N+1, "InjectNVidia", false); - } else if (gConf.GfxPropertiesArray[i].Vendor == Ati) { - SubScreen->AddMenuItemInput(N+1, "InjectATI", false); - } else if (gConf.GfxPropertiesArray[i].Vendor == Intel) { - SubScreen->AddMenuItemInput(N+1, "InjectIntel", false); - } else { - SubScreen->AddMenuItemInput(N+1, "InjectX3", false); - } - UINTN Ven = 97; //it can be used for non Ati, Nvidia, Intel in QEMU for example - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - Ven = 95; - } else if (gConf.GfxPropertiesArray[i].Vendor == Ati) { - Ven = 94; - } else if (gConf.GfxPropertiesArray[i].Vendor == Intel) { - Ven = 96; - } +static EFI_STATUS StartEFIImage(IN EFI_DEVICE_PATH *DevicePath, + IN CONST XString8Array& LoadOptions, IN CONST XStringW& LoadOptionsPrefix, + IN CONST XStringW& ImageTitle, + OUT UINTN *ErrorInStep, + OUT EFI_HANDLE *NewImageHandle) +{ + EFI_STATUS Status; + EFI_HANDLE ChildImageHandle = NULL; - if ((gConf.GfxPropertiesArray[i].Vendor == Ati) || (gConf.GfxPropertiesArray[i].Vendor == Intel)) { - SubScreen->AddMenuItemInput(109, "DualLink:", true); - } - if (gConf.GfxPropertiesArray[i].Vendor == Ati) { - SubScreen->AddMenuItemInput(114, "DeInit:", true); - } + Status = LoadEFIImage(DevicePath, ImageTitle, ErrorInStep, &ChildImageHandle); + if (!EFI_ERROR(Status)) { + Status = StartEFILoadedImage(ChildImageHandle, LoadOptions, LoadOptionsPrefix, ImageTitle, ErrorInStep); + } - SubScreen->AddMenuItemInput(Ven, "FakeID:", true); + if (NewImageHandle != NULL) { + *NewImageHandle = ChildImageHandle; + } + return Status; +} - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - SubScreen->AddMenuItemInput(N+2, "DisplayCFG:", true); - } else if (gConf.GfxPropertiesArray[i].Vendor == Ati) { - SubScreen->AddMenuItemInput(N+2, "FBConfig:", true); - } else /*if (gGraphics[i].Vendor == Intel)*/{ - SubScreen->AddMenuItemInput(N+2, "*-platform-id:", true); - } - // ErmaC: NvidiaGeneric entry - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - SubScreen->AddMenuItemInput(55, "Generic NVIDIA name", false); - SubScreen->AddMenuItemInput(110, "NVIDIA No EFI", false); - SubScreen->AddMenuItemInput(111, "NVIDIA Single", false); - SubScreen->AddMenuItemInput(56, "Use NVIDIA WEB drivers", false); +#ifdef DUMP_KERNEL_KEXT_PATCHES +void DumpKernelAndKextPatches(KERNEL_AND_KEXT_PATCHES *Patches) +{ + if (!Patches) { + DBG("Kernel and Kext Patches null pointer\n"); + return; + } + DBG("Kernel and Kext Patches at %llx:\n", (uintptr_t)Patches); + DBG("\tAllowed: %c\n", GlobalConfig.KextPatchesAllowed ? 'y' : 'n'); + DBG("\tDebug: %c\n", Patches->KPDebug ? 'y' : 'n'); +// DBG("\tKernelCpu: %c\n", Patches->KPKernelCpu ? 'y' : 'n'); + DBG("\tKernelLapic: %c\n", Patches->KPKernelLapic ? 'y' : 'n'); + DBG("\tKernelXCPM: %c\n", Patches->KPKernelXCPM ? 'y' : 'n'); + DBG("\tKernelPm: %c\n", Patches->KPKernelPm ? 'y' : 'n'); + DBG("\tAppleIntelCPUPM: %c\n", Patches->KPAppleIntelCPUPM ? 'y' : 'n'); + DBG("\tAppleRTC: %c\n", Patches->KPAppleRTC ? 'y' : 'n'); + // Dell smbios truncate fix + DBG("\tDellSMBIOSPatch: %c\n", Patches->KPDELLSMBIOS ? 'y' : 'n'); + DBG("\tFakeCPUID: 0x%X\n", Patches->FakeCPUID); + DBG("\tATIController: %s\n", Patches->KPATIConnectorsController.isEmpty() ? "(null)": Patches->KPATIConnectorsController.c_str()); + DBG("\tATIDataLength: %zu\n", Patches->KPATIConnectorsData.size()); + DBG("\t%zu Kexts to load\n", Patches->ForceKextsToLoad.size()); + if (Patches->ForceKextsToLoad.size()) { + size_t i = 0; + for (; i < Patches->ForceKextsToLoad.size(); ++i) { + DBG("\t KextToLoad[%zu]: %ls\n", i, Patches->ForceKextsToLoad[i].wc_str()); } - - if (gConf.GfxPropertiesArray[i].Vendor == Intel) { - continue; + } + DBG("\t%zu Kexts to patch\n", Patches->KextPatches.size()); + if (Patches->KextPatches.size()) { + size_t i = 0; + for (; i < Patches->KextPatches.size(); ++i) { + if (Patches->KextPatches[i].IsPlistPatch) { + DBG("\t KextPatchPlist[%zu]: %zu bytes, %s\n", i, Patches->KextPatches[i].Data.size(), Patches->KextPatches[i].Name.c_str()); + } else { + DBG("\t KextPatch[%zu]: %zu bytes, %s\n", i, Patches->KextPatches[i].Data.size(), Patches->KextPatches[i].Name.c_str()); + } } - SubScreen->AddMenuItemInput(N+3, "Ports:", true); + } +} +#endif +void LOADER_ENTRY::FilterKextPatches() +{ + if ( GlobalConfig.KextPatchesAllowed && KernelAndKextPatches.KextPatches.size() > 0 ) { + DBG("Filtering KextPatches:\n"); + for (size_t i = 0; i < KernelAndKextPatches.KextPatches.size(); i++) { + DBG(" - [%02zu]: %s :: %s :: [OS: %s | MatchOS: %s | MatchBuild: %s]", + i, + KernelAndKextPatches.KextPatches[i].Label.c_str(), + KernelAndKextPatches.KextPatches[i].IsPlistPatch ? "PlistPatch" : "BinPatch", + macOSVersion.asString().c_str(), + KernelAndKextPatches.KextPatches[i].MatchOS.notEmpty() ? KernelAndKextPatches.KextPatches[i].MatchOS.c_str() : "All", + KernelAndKextPatches.KextPatches[i].MatchBuild.notEmpty() ? KernelAndKextPatches.KextPatches[i].MatchBuild.c_str() : "All" + ); + if (!gSettings.KernelAndKextPatches.KextPatches[i].MenuItem.BValue) { + KernelAndKextPatches.KextPatches[i].MenuItem.BValue = false; + DBG(" ==> disabled by user\n"); + continue; + } + KernelAndKextPatches.KextPatches[i].MenuItem.BValue = true; + if ((BuildVersion.notEmpty()) && (KernelAndKextPatches.KextPatches[i].MatchBuild.notEmpty())) { + KernelAndKextPatches.KextPatches[i].MenuItem.BValue = KernelAndKextPatches.KextPatches[i].IsPatchEnabledByBuildNumber(BuildVersion); + DBG(" ==> %s\n", KernelAndKextPatches.KextPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); + continue; + } - if (gConf.GfxPropertiesArray[i].Vendor == Nvidia) { - SubScreen->AddMenuItemInput(N+4, "NVCAP:", true); - } else { - SubScreen->AddMenuItemInput(N+4, "Connectors:", true); - SubScreen->AddMenuItemInput(50, "RefCLK:", true); + KernelAndKextPatches.KextPatches[i].MenuItem.BValue = KernelAndKextPatches.KextPatches[i].IsPatchEnabled(macOSVersion); + DBG(" ==> %s\n", KernelAndKextPatches.KextPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); } - SubScreen->AddMenuItemInput(N+5, "Load Video Bios", false); } - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; } -// ErmaC: Audio submenu -REFIT_ABSTRACT_MENU_ENTRY *SubMenuAudio() +void LOADER_ENTRY::FilterKernelPatches() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - // create the entry in the main menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_AUDIO, "Audio tuning->"_XS8); + if ( GlobalConfig.KernelPatchesAllowed && KernelAndKextPatches.KernelPatches.notEmpty() ) { + DBG("Filtering KernelPatches:\n"); + for (size_t i = 0; i < KernelAndKextPatches.KernelPatches.size(); ++i) { + DBG(" - [%02zu]: %s :: [OS: %s | MatchOS: %s | MatchBuild: %s]", + i, + KernelAndKextPatches.KernelPatches[i].Label.c_str(), + macOSVersion.asString().c_str(), + KernelAndKextPatches.KernelPatches[i].MatchOS.notEmpty() ? KernelAndKextPatches.KernelPatches[i].MatchOS.c_str() : "All", + KernelAndKextPatches.KernelPatches[i].MatchBuild.notEmpty() ? KernelAndKextPatches.KernelPatches[i].MatchBuild.c_str() : "All" + ); + if (!gSettings.KernelAndKextPatches.KernelPatches[i].MenuItem.BValue) { + KernelAndKextPatches.KernelPatches[i].MenuItem.BValue = false; + DBG(" ==> disabled by user\n"); + continue; + } + KernelAndKextPatches.KernelPatches[i].MenuItem.BValue = true; + if ((BuildVersion.notEmpty()) && (KernelAndKextPatches.KernelPatches[i].MatchBuild.notEmpty())) { + KernelAndKextPatches.KernelPatches[i].MenuItem.BValue = KernelAndKextPatches.KernelPatches[i].IsPatchEnabledByBuildNumber(BuildVersion); + DBG(" ==> %s by build\n", KernelAndKextPatches.KernelPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); + continue; + } - // submenu description - SubScreen->AddMenuInfoLine_f("Choose options to tune the HDA devices"); - SubScreen->AddMenuInfoLine_f("Number of Audio Controller%s=%zu", ((gConf.HdaPropertiesArray.size()!=1)?"s":""), gConf.HdaPropertiesArray.size()); - for (UINTN i = 0 ; i < gConf.HdaPropertiesArray.size() ; i++) { - SubScreen->AddMenuInfoLine_f("%llu) %ls [%04hX][%04hX]", - (i+1), - gConf.HdaPropertiesArray[i].controller_name.wc_str(), - gConf.HdaPropertiesArray[i].controller_vendor_id, - gConf.HdaPropertiesArray[i].controller_device_id - ); + KernelAndKextPatches.KernelPatches[i].MenuItem.BValue = KernelAndKextPatches.KernelPatches[i].IsPatchEnabled(macOSVersion); + DBG(" ==> %s by OS\n", KernelAndKextPatches.KernelPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); + } } +} - //SubScreen->AddMenuItemInput(59, "HDAInjection", false); - if (gSettings.Devices.Audio.HDAInjection) { - SubScreen->AddMenuItemInput(60, "HDALayoutId:", true); +void LOADER_ENTRY::FilterBootPatches() +{ + if ( KernelAndKextPatches.BootPatches.notEmpty() ) { + DBG("Filtering BootPatches:\n"); + for (size_t i = 0; i < KernelAndKextPatches.BootPatches.size(); ++i) { + DBG(" - [%02zu]: %s :: [OS: %s | MatchOS: %s | MatchBuild: %s]", + i, + KernelAndKextPatches.BootPatches[i].Label.c_str(), + macOSVersion.asString().c_str(), + KernelAndKextPatches.BootPatches[i].MatchOS.notEmpty() ? KernelAndKextPatches.BootPatches[i].MatchOS.c_str() : "All", + KernelAndKextPatches.BootPatches[i].MatchBuild.notEmpty() ? KernelAndKextPatches.BootPatches[i].MatchBuild.c_str() : "All" + ); + if (!gSettings.KernelAndKextPatches.BootPatches[i].MenuItem.BValue) { + DBG(" ==> disabled by user\n"); + continue; + } + KernelAndKextPatches.BootPatches[i].MenuItem.BValue = true; + if ((BuildVersion.notEmpty()) && (KernelAndKextPatches.BootPatches[i].MatchBuild.notEmpty())) { + KernelAndKextPatches.BootPatches[i].MenuItem.BValue = KernelAndKextPatches.BootPatches[i].IsPatchEnabledByBuildNumber(BuildVersion); + DBG(" ==> %s by build\n", KernelAndKextPatches.BootPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); + continue; + } + + KernelAndKextPatches.BootPatches[i].MenuItem.BValue = KernelAndKextPatches.BootPatches[i].IsPatchEnabled(macOSVersion); + DBG(" ==> %s by OS\n", KernelAndKextPatches.BootPatches[i].MenuItem.BValue ? "allowed" : "not allowed"); + + } } +} - // avaiable configuration - SubScreen->AddMenuItemInput(57, "ResetHDA", false); - SubScreen->AddMenuItemInput(58, "AFGLowPowerState", false); - - // return - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; +// +// Null ConOut OutputString() implementation - for blocking +// text output from boot.efi when booting in graphics mode +// +EFI_STATUS EFIAPI +NullConOutOutputString(IN EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *, IN CONST CHAR16 *) { + return EFI_SUCCESS; } -#define nya(x) x/10,x%10 -REFIT_ABSTRACT_MENU_ENTRY* SubMenuSpeedStep() +void CheckEmptyFB() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_CPU, "CPU tuning->"_XS8); - SubScreen->AddMenuInfoLine_f("%s", gCPUStructure.BrandString.c_str()); - SubScreen->AddMenuInfoLine_f("Model: %2X/%2X/%2X", - gCPUStructure.Family, gCPUStructure.Model, gCPUStructure.Stepping); - SubScreen->AddMenuInfoLine_f("Cores: %d Threads: %d", - gCPUStructure.Cores, gCPUStructure.Threads); - SubScreen->AddMenuInfoLine_f("FSB speed MHz: %llu", - DivU64x32(gCPUStructure.FSBFrequency, Mega)); - SubScreen->AddMenuInfoLine_f("CPU speed MHz: %llu", - DivU64x32(gCPUStructure.CPUFrequency, Mega)); - SubScreen->AddMenuInfoLine_f("Ratio: Min=%d.%d Max=%d.%d Turbo=%d.%d/%d.%d/%d.%d/%d.%d", - nya(gCPUStructure.MinRatio), nya(gCPUStructure.MaxRatio), - nya(gCPUStructure.Turbo4), nya(gCPUStructure.Turbo3), nya(gCPUStructure.Turbo2), nya(gCPUStructure.Turbo1)); - - - SubScreen->AddMenuItemInput(76, "Cores enabled:", true); - SubScreen->AddMenuItemInput(6, "Halt Enabler", false); - SubScreen->AddMenuItemInput(7, "PLimitDict:", true); - SubScreen->AddMenuItemInput(8, "UnderVoltStep:", true); - SubScreen->AddMenuItemInput(88, "DoubleFirstState", false); - SubScreen->AddMenuItemInput(5, "GeneratePStates", false); - SubScreen->AddMenuItemInput(9, "GenerateCStates", false); - SubScreen->AddMenuItemInput(10, "EnableC2", false); - SubScreen->AddMenuItemInput(11, "EnableC4", false); - SubScreen->AddMenuItemInput(12, "EnableC6", false); - SubScreen->AddMenuItemInput(89, "EnableC7", false); - SubScreen->AddMenuItemInput(13, "Use SystemIO", false); - SubScreen->AddMenuItemInput(75, "C3Latency:", true); - SubScreen->AddMenuItemInput(19, "BusSpeed [kHz]:", true); - SubScreen->AddMenuItemInput(14, "QPI [MHz]:", true); - SubScreen->AddMenuItemInput(77, "Saving Mode:", true); - SubScreen->AddMenuItemInput(15, "PatchAPIC", false); //-> move to ACPI? - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + XBool EmptyFB = (GlobalConfig.IgPlatform == 0x00050000) || + (GlobalConfig.IgPlatform == 0x01620007) || + (GlobalConfig.IgPlatform == 0x04120004) || + (GlobalConfig.IgPlatform == 0x19120001) || + (GlobalConfig.IgPlatform == 0x59120003) || + (GlobalConfig.IgPlatform == 0x9BC80003) || + (GlobalConfig.IgPlatform == 0x3E910003); + if (EmptyFB) { + gSettings.Smbios.gPlatformFeature |= PT_FEATURE_HAS_HEADLESS_GPU; + } else { + gSettings.Smbios.gPlatformFeature &= ~PT_FEATURE_HAS_HEADLESS_GPU; + } } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuKextPatches() +size_t setKextAtPos(XObjArray* kextArrayPtr, const XString8& kextName, size_t pos) { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_INPUT_DIALOG *InputBootArgs; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_KEXTS, "Custom kexts patches->"_XS8); + XObjArray& kextArray = *kextArrayPtr; - for ( size_t Index = 0; Index < gSettings.KernelAndKextPatches.KextPatches.size(); Index++) { - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("%90s", gSettings.KernelAndKextPatches.KextPatches[Index].Label.c_str()); -// InputBootArgs->Tag = TAG_INPUT; - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(gSettings.KernelAndKextPatches.KextPatches[Index].MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); + for (size_t kextIdx = 0 ; kextIdx < kextArray.size() ; kextIdx++ ) { + if ( kextArray[kextIdx].FileName.contains(kextName) ) { + if ( pos >= kextArray.size() ) { + log_technical_bug("pos >= kextArray.size()"); + return kextArray.size() - 1 ; // If we're here, kextArray.size() is at least 1 + } + if ( pos == kextIdx ) return pos+1; + if ( pos > kextIdx ) pos -= 1; + SIDELOAD_KEXT* kextToMove = &kextArray[kextIdx]; + kextArray.RemoveWithoutFreeingAtIndex(kextIdx); + kextArray.InsertRef(kextToMove, pos, false); + return pos+1; + } } - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + return pos; } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuKextBlockInjection(const XString8& UniSysVer) +static XStringW getDriversPath() { - REFIT_MENU_ITEM_OPTIONS *Entry = NULL; - REFIT_MENU_SCREEN *SubScreen = NULL; - REFIT_INPUT_DIALOG *InputBootArgs; - - for ( size_t idx = 0 ; idx < InjectKextList.size() ; idx ++ ) { - SIDELOAD_KEXT& Kext = InjectKextList[idx]; - if ( Kext.KextDirNameUnderOEMPath == UniSysVer ) { - if ( SubScreen == NULL ) { - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_KEXT_INJECT, S8Printf("%s->", UniSysVer.c_str())); - SubScreen->AddMenuInfoLine_f("Choose/check kext to disable:"); - } - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("%ls, v.%ls", Kext.FileName.wc_str(), Kext.Version.wc_str()); -// InputBootArgs->Tag = TAG_INPUT; - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(Kext.MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - - for ( size_t idxPlugin = 0 ; idxPlugin < Kext.PlugInList.size() ; idxPlugin ++ ) { - SIDELOAD_KEXT& plugInKext = Kext.PlugInList[idxPlugin]; - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf(" |-- %ls, v.%ls", plugInKext.FileName.wc_str(), plugInKext.Version.wc_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(plugInKext.MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - } - } - - if ( SubScreen != NULL ) SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; +#if defined(MDE_CPU_X64) + if (gFirmwareClover) { + if (FileExists(&self.getCloverDir(), L"drivers\\BIOS")) { + return L"drivers\\BIOS"_XSW; + } else { + return L"drivers64"_XSW; //backward compatibility + } + } else if (FileExists(&self.getCloverDir(), L"drivers\\5142")) { // can be excluded as obsolete + return L"drivers\\5142"_XSW; + } else if (FileExists(&self.getCloverDir(), L"drivers\\UEFI")) { + return L"drivers\\UEFI"_XSW; + } else { + return L"drivers64UEFI"_XSW; + } +#else + return L"drivers32"_XSW; +#endif } -LOADER_ENTRY* LOADER_ENTRY::SubMenuKextInjectMgmt() +#ifdef JIEF_DEBUG +void debugStartImageWithOC() { - LOADER_ENTRY *SubEntry; - REFIT_MENU_SCREEN *SubSubScreen; - - SubEntry = new LOADER_ENTRY; - NewEntry_(SubEntry, &SubSubScreen, ActionEnter, SCREEN_SYSTEM, "Block injected kexts->"_XS8); - SubEntry->Flags = Flags; - if (macOSVersion.notEmpty()) { - - XString8 OSVersionKextsDirName; // declare here to avoid multiple allocation - - { - XString8 ShortOSVersion = macOSVersion.nbElement() == 1 ? macOSVersion.asString(1) : macOSVersion.asString(macOSVersion.nbElement()-1); - SubSubScreen->AddMenuInfoLine_f("Block injected kexts for target version of macOS: %s", ShortOSVersion.c_str()); - } - - // Add kext from 10 or 11 - { - OSVersionKextsDirName = macOSVersion.asString(1); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - OSVersionKextsDirName.S8Catf("_%s", getSuffixForMacOsVersion(LoaderType).c_str()); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - } - - // Add kext from 10(or 11).{version} - { - OSVersionKextsDirName = macOSVersion.asString(2); - if ( macOSVersion.elementAt(1) == -1 ) OSVersionKextsDirName.S8Catf(".0"); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - OSVersionKextsDirName.S8Catf("_%s", getSuffixForMacOsVersion(LoaderType).c_str()); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - } - - // Add kext from : - // 10(or 1*).{version}.0 if NO minor version - // 10(or 1*).{version}.{minor version} if minor version is > 0 - if ( macOSVersion.nbElement() >= 2 ) - { - OSVersionKextsDirName = macOSVersion.asString(3); - if ( macOSVersion.elementAt(1) == -1 ) OSVersionKextsDirName.S8Catf(".0"); - if ( macOSVersion.elementAt(2) == -1 ) OSVersionKextsDirName.S8Catf(".0"); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - OSVersionKextsDirName.S8Catf("_%s", getSuffixForMacOsVersion(LoaderType).c_str()); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection(OSVersionKextsDirName), true); - } - } - else { - SubSubScreen->AddMenuInfoLine_f("Block injected kexts for unknown macOS version"); - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection("Unknown"_XS8), true); - } - - XStringW kextDir; - kextDir = GetOtherKextsDir(true); - if ( kextDir.notEmpty() ) { - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection("Other"_XS8), true); - } - kextDir = GetOtherKextsDir(false); - if ( kextDir.notEmpty() ) { - SubSubScreen->AddMenuEntry(SubMenuKextBlockInjection("Off"_XS8), true); - } - - SubSubScreen->AddMenuEntry(&MenuEntryReturn, false); - return SubEntry; + MsgLog("debugStartImageWithOC\n"); + UINT64 CPUFrequencyFromART; + InternalCalculateARTFrequencyIntel(&CPUFrequencyFromART, NULL, 1); + + EFI_LOADED_IMAGE* OcLoadedImage; + EFI_STATUS Status = gBS->HandleProtocol(gImageHandle, &gEfiLoadedImageProtocolGuid, (void **) &OcLoadedImage); + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL* FileSystem = OcLocateFileSystem(OcLoadedImage->DeviceHandle, OcLoadedImage->FilePath); + Status = OcStorageInitFromFs(&mOpenCoreStorage, FileSystem, NULL, NULL, self.getCloverDirFullPath().wc_str(), NULL); + + Status = ClOcReadConfigurationFile(&mOpenCoreStorage, L"config-oc.plist", &mOpenCoreConfiguration); + if ( EFI_ERROR(Status) ) panic("ClOcReadConfigurationFile"); + + mOpenCoreConfiguration.Misc.Debug.Target = 0; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Misc.Boot.PickerMode, "Builtin"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Misc.Security.DmgLoading, "Any"); + mOpenCoreConfiguration.Uefi.Quirks.IgnoreInvalidFlexRatio = 0; + + mOpenCoreConfiguration.Uefi.Quirks.TscSyncTimeout = 0; + + OcMain(&mOpenCoreStorage, NULL); + + XStringW devicePathToLookFor; +// devicePathToLookFor.takeValueFrom("PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x0,0x0,0x0)/HD(4,GPT,CA224585-830E-4274-5826-1ACB6DA08A4E,0x299F000,0x4AE6310)/VenMedia(BE74FCF7-0B7C-49F3-9147-01F4042E6842,1ABE434C8D0357398516CFDF0A9DD7EF)"); // Jief High Sierra DevicePath + devicePathToLookFor.takeValueFrom("PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x0,0x0,0x0)/HD(2,GPT,D8C7DA82-1E4C-4579-BA7C-6737A5D43464,0x64028,0x1BF08E8)"); // Jief Big Sur Install device path + UINTN HandleCount = 0; + EFI_HANDLE *Handles = NULL; + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &HandleCount, &Handles); + UINTN HandleIndex = 0; + for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) { + EFI_DEVICE_PATH_PROTOCOL* DevicePath = DevicePathFromHandle(Handles[HandleIndex]); + CHAR16* UnicodeDevicePath = ConvertDevicePathToText(DevicePath, false, false); + MsgLog("debugStartImageWithOC : path %ls\n", UnicodeDevicePath); + if ( StrCmp(devicePathToLookFor.wc_str(), UnicodeDevicePath) == 0 ) break; + } + if ( HandleIndex < HandleCount ) + { + EFI_DEVICE_PATH_PROTOCOL* jfkImagePath = FileDevicePath(Handles[HandleIndex], L"\\System\\Library\\CoreServices\\boot.efi"); + CHAR16* UnicodeDevicePath = ConvertDevicePathToText (jfkImagePath, false, false); (void)UnicodeDevicePath; + + EFI_HANDLE EntryHandle = NULL; + + // point to InternalEfiLoadImage from OC + Status = gBS->LoadImage ( + false, + gImageHandle, + jfkImagePath, + NULL, + 0, + &EntryHandle + ); + if ( EFI_ERROR(Status) ) return; // TODO message ? + + EFI_LOADED_IMAGE *LoadedImage = NULL; + EFI_STATUS OptionalStatus = gBS->HandleProtocol ( + EntryHandle, + &gEfiLoadedImageProtocolGuid, + (void **) &LoadedImage + ); + if ( EFI_ERROR(OptionalStatus) ) return; // TODO message ? + + // XStringW LoadOptionsAsXStringW = SWPrintf("%s ", LoadOptions.ConcatAll(" "_XS8).c_str()); + XStringW LoadOptionsAsXStringW = SWPrintf("boot.efi -v -no_compat_check slide=0 kext-dev-mode=1 keepsyms=1 -wegdbg igfxgl=1 bpr_probedelay=200 bpr_initialdelay=400 bpr_postresetdelay=400 "); + LoadedImage->LoadOptions = (void*)LoadOptionsAsXStringW.wc_str(); + LoadedImage->LoadOptionsSize = (UINT32)LoadOptionsAsXStringW.sizeInBytesIncludingTerminator(); + + // point to OcStartImage from OC + Status = gBS->StartImage (EntryHandle, 0, NULL); + if ( EFI_ERROR(Status) ) return; // TODO message ? + }else{ + MsgLog("debugStartImageWithOC : not found\n"); + } } +#endif - -REFIT_ABSTRACT_MENU_ENTRY* SubMenuKernelPatches() +void LOADER_ENTRY::DelegateKernelPatches() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_INPUT_DIALOG *InputBootArgs; + XObjArray selectedPathArray; + for (size_t kernelPatchIdx = 0 ; kernelPatchIdx < KernelAndKextPatches.KernelPatches.size() ; kernelPatchIdx++ ) + { + if ( KernelAndKextPatches.KernelPatches[kernelPatchIdx].MenuItem.BValue ) + selectedPathArray.AddReference(&KernelAndKextPatches.KernelPatches[kernelPatchIdx], false); + } + for (size_t kextPatchIdx = 0 ; kextPatchIdx < KernelAndKextPatches.KextPatches.size() ; kextPatchIdx++ ) + { + if ( KernelAndKextPatches.KextPatches[kextPatchIdx].MenuItem.BValue ) + selectedPathArray.AddReference(&KernelAndKextPatches.KextPatches[kextPatchIdx], false); + } + mOpenCoreConfiguration.Kernel.Patch.Count = (UINT32)selectedPathArray.size(); + mOpenCoreConfiguration.Kernel.Patch.AllocCount = mOpenCoreConfiguration.Kernel.Patch.Count; + mOpenCoreConfiguration.Kernel.Patch.ValueSize = sizeof(__typeof_am__(**mOpenCoreConfiguration.Kernel.Patch.Values)); + mOpenCoreConfiguration.Kernel.Patch.Values = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Patch.Values)*)malloc(mOpenCoreConfiguration.Kernel.Patch.AllocCount*sizeof(__typeof_am__(*mOpenCoreConfiguration.Kernel.Patch.Values))); + memset(mOpenCoreConfiguration.Kernel.Patch.Values, 0, mOpenCoreConfiguration.Kernel.Patch.AllocCount*sizeof(*mOpenCoreConfiguration.Kernel.Patch.Values)); + + UINT32 FakeCPUID = gSettings.Smbios.SFakeCPU; + if (FakeCPUID != 0) gFakeCPUID = FakeCPUID; + DBG("Set FakeCPUID: 0x%X\n", gFakeCPUID); - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_KERNELS, "Custom kernel patches->"_XS8); + memset(mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Data, 0, sizeof(mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Data)); + memset(mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Mask, 0, sizeof(mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Mask)); + mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Data[0] = gFakeCPUID; + mOpenCoreConfiguration.Kernel.Emulate.Cpuid1Mask[0] = 0xFFFFFFFF; - for (size_t Index = 0; Index < gSettings.KernelAndKextPatches.KernelPatches.size(); Index++) { - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("%90s", gSettings.KernelAndKextPatches.KernelPatches[Index].Label.c_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(gSettings.KernelAndKextPatches.KernelPatches[Index].MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); + for (size_t kextPatchIdx = 0 ; kextPatchIdx < selectedPathArray.size() ; kextPatchIdx++ ) + { + const ABSTRACT_KEXT_OR_KERNEL_PATCH& kextPatch = selectedPathArray[kextPatchIdx]; //as well as kernel patches + DBG("Bridge %s patch to OC : %s\n", kextPatch.getName().c_str(), kextPatch.Label.c_str()); + mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx] = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Patch.Values))AllocateZeroPool(mOpenCoreConfiguration.Kernel.Patch.ValueSize); // sizeof(OC_KERNEL_ADD_ENTRY) == 680 + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Arch, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Scheme.KernelArch)); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Base, kextPatch.ProcedureName.c_str()); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Comment, kextPatch.Label.c_str()); + mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Count = (UINT32)kextPatch.Count; + mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Enabled = 1; + + OC_DATA_ASSIGN_N(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Find, kextPatch.Find.data(), kextPatch.Find.size()); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Identifier, kextPatch.getName().c_str()); + mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Limit = (UINT32)kextPatch.SearchLen; + OC_DATA_ASSIGN_N(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Mask, kextPatch.MaskFind.data(), kextPatch.MaskFind.size()); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->MaxKernel, ""); // it has been filtered, so we don't need to set Min and MaxKernel + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->MinKernel, ""); + OC_DATA_ASSIGN_N(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Replace, kextPatch.Replace.data(), kextPatch.Replace.size()); + OC_DATA_ASSIGN_N(mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->ReplaceMask, kextPatch.MaskReplace.data(), kextPatch.MaskReplace.size()); + mOpenCoreConfiguration.Kernel.Patch.Values[kextPatchIdx]->Skip = (UINT32)kextPatch.Skip; } - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuBootPatches() +void LOADER_ENTRY::StartLoader() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_INPUT_DIALOG *InputBootArgs; + EFI_STATUS Status; + EFI_TEXT_STRING ConOutOutputString = 0; + EFI_HANDLE ImageHandle = NULL; + EFI_LOADED_IMAGE *LoadedImage = NULL; + CONST CHAR8 *InstallerVersion; - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_BOOTER, "Custom booter patches->"_XS8); + DbgHeader("StartLoader"); - for (size_t Index = 0; Index < gSettings.KernelAndKextPatches.BootPatches.size(); Index++) { - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("%90s", gSettings.KernelAndKextPatches.BootPatches[Index].Label.c_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(gSettings.KernelAndKextPatches.BootPatches[Index].MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); + DBG("Starting %ls\n", FileDevicePathToXStringW(DevicePath).wc_str()); +#ifdef JIEF_DEBUG + displayFreeMemory("LOADER_ENTRY::StartLoader()"_XS8); +#endif +// while ( OcCountFreePages(NULL) > 300000 && AllocatePages(100) ) /*DBG("Free memory : %lld\n", OcCountFreePages(NULL))*/; +// displayFreeMemory(); + + if (Settings.notEmpty()) { + DBG(" Settings: %ls\n", Settings.wc_str()); + Status = gConf.ReLoadConfig(Settings); + if (!EFI_ERROR(Status)) { + DBG(" - found custom settings for this entry: %ls\n", Settings.wc_str()); + } else { + DBG(" - [!] LoadUserSettings failed: %s\n", efiStrError(Status)); + /* we are not sure of the state of gSettings here... try to boot anyway */ + } + } + + DBG("Finally: ExternalClock=%lluMHz BusSpeed=%llukHz CPUFreq=%uMHz", + DivU64x32(gCPUStructure.ExternalClock + Kilo - 1, Kilo), + DivU64x32(gCPUStructure.FSBFrequency + Kilo - 1, Kilo), + gCPUStructure.MaxSpeed); + if (gSettings.CPU.QPI) { + DBG(" QPI: hw.busfrequency=%lluHz\n", MultU64x32(gSettings.CPU.QPI, Mega)); + } else { + // to match the value of hw.busfrequency in the terminal + DBG(" PIS: hw.busfrequency=%lluHz\n", MultU64x32(LShiftU64(DivU64x32(gCPUStructure.ExternalClock + Kilo - 1, Kilo), 2), Mega)); } + + //Free memory + ConfigsList.setEmpty(); + DsdtsList.setEmpty(); - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + OptionMenu.FreeMenu(); + //there is a place to free memory + // GuiAnime + // mainParser + // BuiltinIcons + // OSIcons -REFIT_ABSTRACT_MENU_ENTRY* SubMenuBinaries() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_BINARIES, "Binaries patching->"_XS8); - - SubScreen->AddMenuInfoLine_f("%s", gCPUStructure.BrandString.c_str()); - SubScreen->AddMenuInfoLine_f("Real CPUID: 0x%06X", gCPUStructure.Signature); - - SubScreen->AddMenuItemInput(64, "Debug", false); - SubScreen->AddMenuInfo_f("----------------------"); - SubScreen->AddMenuItemInput(104, "Fake CPUID:", true); - SubScreen->AddMenuItemInput(91, "Kernel Lapic", false); - SubScreen->AddMenuItemInput(105, "Kernel XCPM", false); - SubScreen->AddMenuItemInput(48, "Kernel PM", false); - SubScreen->AddMenuItemInput(121, "Panic No Kext Dump", false); - SubScreen->AddMenuItemInput(128, "Provide CPU Info", false); - SubScreen->AddMenuEntry(SubMenuKernelPatches(), true); - SubScreen->AddMenuInfo_f("----------------------"); - SubScreen->AddMenuItemInput(46, "AppleIntelCPUPM Patch", false); - SubScreen->AddMenuItemInput(47, "AppleRTC Patch", false); -// SubScreen->AddMenuItemInput(45, "No 8 Apples Patch", false); - SubScreen->AddMenuItemInput(61, "Dell SMBIOS Patch", false); - SubScreen->AddMenuItemInput(115, "Block SkywalkFamily", false); -// SubScreen->AddMenuItemInput(115, "No Caches", false); -// SubScreen->AddMenuItemInput(44, "Kext patching allowed", false); - SubScreen->AddMenuEntry(SubMenuKextPatches(), true); - SubScreen->AddMenuInfo_f("----------------------"); - SubScreen->AddMenuEntry(SubMenuBootPatches(), true); - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + delete ThemeX; + ThemeX = NULL; -REFIT_ABSTRACT_MENU_ENTRY* SubMenuDropTables() -{ - CHAR8 sign[5]; - CHAR8 OTID[9]; - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_INPUT_DIALOG *InputBootArgs; + devprop_free_string(); - sign[4] = 0; - OTID[8] = 0; - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_TABLES, "Tables dropping->"_XS8); +#ifdef NANOSVG_MEMORY_ALLOCATION_TRACE + if ( nsvg__nbDanglingPtr() > 0 ) { + DBG("There is %zu dangling ptr from SVG subsytem\n", nsvg__nbDanglingPtr()); + nsvg__outputDanglingPtr(); + } +#endif +#ifdef JIEF_DEBUG + displayFreeMemory("LOADER_ENTRY::StartLoader() atfer ThemeX deleted"_XS8); +#endif - if (GlobalConfig.ACPIDropTables.notEmpty()) { - for ( size_t idx = 0 ; idx < GlobalConfig.ACPIDropTables.length() ; ++idx ) - { - ACPI_DROP_TABLE& DropTable = GlobalConfig.ACPIDropTables[idx]; - - CopyMem((CHAR8*)&sign, (CHAR8*)&(DropTable.Signature), 4); - CopyMem((CHAR8*)&OTID, (CHAR8*)&(DropTable.TableId), 8); - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("Drop \"%4.4s\" \"%8.8s\" %d", sign, OTID, DropTable.Length); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(DropTable.MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - } + if ( OSTYPE_IS_OSX(LoaderType) || OSTYPE_IS_OSX_RECOVERY(LoaderType) || OSTYPE_IS_OSX_INSTALLER(LoaderType) ) { + + // if OC is NOT initialized with OcMain, we need the following + // OcConfigureLogProtocol ( + // 9, + // 0, + // 2151678018, + // 2147483648, + // OPEN_CORE_LOG_PREFIX_PATH, + // mOpenCoreStorage.FileSystem + // ); + // DEBUG ((DEBUG_INFO, "OC: Log initialized...\n")); + // OcAppleDebugLogInstallProtocol(0); + + DBG("Beginning OC\n"); + + EFI_LOADED_IMAGE* OcLoadedImage; + Status = gBS->HandleProtocol(gImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &OcLoadedImage); + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL* FileSystem = OcLocateFileSystem(OcLoadedImage->DeviceHandle, OcLoadedImage->FilePath); + Status = OcStorageInitFromFs(&mOpenCoreStorage, FileSystem, NULL, NULL, self.getCloverDirFullPath().wc_str(), NULL); + + /* + * Define READ_FROM_OC to have mOpenCoreConfiguration initialized from config-oc.plist + * The boot should work. + * Next, comment out the next lines one by one. Once the boot failed, we got the section that + * holds the setting that makes a difference. + */ + //#define USE_OC_SECTION_Acpi + //#define USE_OC_SECTION_Booter + //#define USE_OC_SECTION_DeviceProperties + //#define USE_OC_SECTION_Kernel + //#define USE_OC_SECTION_Misc + //#define USE_OC_SECTION_Nvram + //#define USE_OC_SECTION_PlatformInfo + //#define USE_OC_SECTION_Uefi + + #if !defined(USE_OC_SECTION_Acpi) && !defined(USE_OC_SECTION_Booter) && !defined(USE_OC_SECTION_DeviceProperties) && !defined(USE_OC_SECTION_Kernel) && !defined(USE_OC_SECTION_Misc) && \ + !defined(USE_OC_SECTION_Nvram) && !defined(USE_OC_SECTION_PlatformInfo) && !defined(USE_OC_SECTION_Uefi) + + memset(&mOpenCoreConfiguration, 0, sizeof(mOpenCoreConfiguration)); +// DBG("config-oc.plist isn't used at all\n"); + + #else + Status = ClOcReadConfigurationFile(&mOpenCoreStorage, L"config-oc.plist", &mOpenCoreConfiguration); + if ( EFI_ERROR(Status) ) panic("ClOcReadConfigurationFile"); + + #ifndef USE_OC_SECTION_Acpi + memset(&mOpenCoreConfiguration.Acpi, 0, sizeof(mOpenCoreConfiguration.Acpi)); + DBG("Erase mOpenCoreConfiguration.Acpi\n"); + #else + DBG("Keep mOpenCoreConfiguration.Acpi\n"); + #endif + #ifndef USE_OC_SECTION_Booter + memset(&mOpenCoreConfiguration.Booter, 0, sizeof(mOpenCoreConfiguration.Booter)); + DBG("Erase mOpenCoreConfiguration.Booter\n"); + #else + DBG("Keep mOpenCoreConfiguration.Booter\n"); + #endif + #ifndef USE_OC_SECTION_DeviceProperties + memset(&mOpenCoreConfiguration.DeviceProperties, 0, sizeof(mOpenCoreConfiguration.DeviceProperties)); + DBG("Erase mOpenCoreConfiguration.DeviceProperties\n"); + #else + DBG("Keep mOpenCoreConfiguration.DeviceProperties\n"); + #endif + #ifndef USE_OC_SECTION_Kernel + memset(&mOpenCoreConfiguration.Kernel, 0, sizeof(mOpenCoreConfiguration.Kernel)); + DBG("Erase mOpenCoreConfiguration.Kernel\n"); + #else + DBG("Keep mOpenCoreConfiguration.Kernel\n"); + for ( size_t i = 0 ; i < mOpenCoreConfiguration.Kernel.Add.Count ; i ++ ) { + OC_KERNEL_ADD_ENTRY* entry = mOpenCoreConfiguration.Kernel.Add.Values[i]; + OC_STRING_ASSIGN(entry->BundlePath, S8Printf("Kexts\\%s", OC_BLOB_GET(&entry->BundlePath)).c_str()); + } - SubScreen->AddMenuItemInput(4, "Drop all OEM SSDT", false); - SubScreen->AddMenuItemInput(113, "Automatic smart merge", false); +// DBG("mOpenCoreConfiguration.Kernel.Add.Count=%d\n", mOpenCoreConfiguration.Kernel.Add.Count); +// for ( size_t i = 0 ; i < mOpenCoreConfiguration.Kernel.Add.Count ; i++ ) +// { +// DBG("mOpenCoreConfiguration.Kernel.Add.Values[%zd]->Identifier=%s\n", i, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[i]->Identifier)); +// DBG("mOpenCoreConfiguration.Kernel.Add.Values[%zd]->BundlePath=%s\n", i, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[i]->BundlePath)); +// DBG("mOpenCoreConfiguration.Kernel.Add.Values[%zd]->PlistPath=%s\n", i, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[i]->PlistPath)); +// } + #endif + #ifndef USE_OC_SECTION_Misc + memset(&mOpenCoreConfiguration.Misc, 0, sizeof(mOpenCoreConfiguration.Misc)); + DBG("Erase mOpenCoreConfiguration.Misc\n"); + #else + DBG("Keep mOpenCoreConfiguration.Misc\n"); + #endif + #ifndef USE_OC_SECTION_Nvram + memset(&mOpenCoreConfiguration.Nvram, 0, sizeof(mOpenCoreConfiguration.Nvram)); + DBG("Erase mOpenCoreConfiguration.Nvram\n"); + #else + DBG("Keep mOpenCoreConfiguration.Nvram\n"); + #endif + #ifndef USE_OC_SECTION_PlatformInfo + memset(&mOpenCoreConfiguration.PlatformInfo, 0, sizeof(mOpenCoreConfiguration.PlatformInfo)); + DBG("Erase mOpenCoreConfiguration.PlatformInfo\n"); + #else + DBG("Keep mOpenCoreConfiguration.PlatformInfo\n"); + #endif + #ifndef USE_OC_SECTION_Uefi + memset(&mOpenCoreConfiguration.Uefi, 0, sizeof(mOpenCoreConfiguration.Uefi)); + DBG("Erase mOpenCoreConfiguration.Uefi\n"); + #else + DBG("Keep mOpenCoreConfiguration.Uefi\n"); + // memset(&mOpenCoreConfiguration.Uefi.Apfs, 0, sizeof(mOpenCoreConfiguration.Uefi.Apfs)); + // memset(&mOpenCoreConfiguration.Uefi.Audio, 0, sizeof(mOpenCoreConfiguration.Uefi.Audio)); + // memset(&mOpenCoreConfiguration.Uefi.ConnectDrivers, 0, sizeof(mOpenCoreConfiguration.Uefi.ConnectDrivers)); + // memset(&mOpenCoreConfiguration.Uefi.Drivers, 0, sizeof(mOpenCoreConfiguration.Uefi.Drivers)); + // memset(&mOpenCoreConfiguration.Uefi.Input, 0, sizeof(mOpenCoreConfiguration.Uefi.Input)); + // memset(&mOpenCoreConfiguration.Uefi.Output, 0, sizeof(mOpenCoreConfiguration.Uefi.Output)); + // memset(&mOpenCoreConfiguration.Uefi.ProtocolOverrides, 0, sizeof(mOpenCoreConfiguration.Uefi.ProtocolOverrides)); + // memset(&mOpenCoreConfiguration.Uefi.Quirks, 0, sizeof(mOpenCoreConfiguration.Uefi.Quirks)); + // memset(&mOpenCoreConfiguration.Uefi.ReservedMemory, 0, sizeof(mOpenCoreConfiguration.Uefi.ReservedMemory)); // doesn't matter + #endif + + #endif + + + + if ( gSettings.Boot.DebugLog ) { + mOpenCoreConfiguration.Misc.Debug.AppleDebug = true; + mOpenCoreConfiguration.Misc.Debug.ApplePanic = true; + + #ifndef LESS_DEBUG + mOpenCoreConfiguration.Misc.Debug.DisplayLevel = 0x80400042; + #else + mOpenCoreConfiguration.Misc.Debug.DisplayLevel = 0x80000042; + #endif + mOpenCoreConfiguration.Misc.Debug.Target = 0x41; + } else { + #ifdef JIEF_DEBUG + egSetGraphicsModeEnabled(false); + mOpenCoreConfiguration.Misc.Debug.ApplePanic = true; + mOpenCoreConfiguration.Misc.Debug.DisplayLevel = 0x80000042; + mOpenCoreConfiguration.Misc.Debug.Target = 0x3; + #endif + } - for ( size_t idx = 0 ; idx < ACPIPatchedAML.size() ; ++idx) { - ACPI_PATCHED_AML& ACPIPatchedAMLTmp = ACPIPatchedAML[idx]; - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("Drop \"%s\"", ACPIPatchedAMLTmp.FileName.c_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &(ACPIPatchedAMLTmp.MenuItem); - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } + #ifndef USE_OC_SECTION_Misc + OC_STRING_ASSIGN(mOpenCoreConfiguration.Misc.Security.SecureBootModel, "Disabled"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Misc.Security.Vault, "Optional"); + #endif + #ifdef USE_OC_SECTION_Nvram + mOpenCoreConfiguration.Nvram.WriteFlash = true; + #endif +#ifndef USE_OC_SECTION_Uefi + mOpenCoreConfiguration.Uefi.Quirks.ForceOcWriteFlash = gSettings.Quirks.OcBooterQuirks.ForceOcWriteFlash; +#endif - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + #ifndef USE_OC_SECTION_Booter -REFIT_ABSTRACT_MENU_ENTRY* SubMenuSmbios() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_SMBIOS, "SMBIOS settings->"_XS8); - - SubScreen->AddMenuInfoLine_f("%s", gCPUStructure.BrandString.c_str()); - SubScreen->AddMenuInfoLine_f("%s", GlobalConfig.OEMProductFromSmbios.c_str()); - SubScreen->AddMenuInfoLine_f("with board %s", GlobalConfig.OEMBoardFromSmbios.c_str()); - - SubScreen->AddMenuItemInput(78, "Product Name:", true); - SubScreen->AddMenuItemInput(79, "Product Version:", true); - SubScreen->AddMenuItemInput(80, "Product SN:", true); - SubScreen->AddMenuItemInput(131, "Fake CPUID:", true); - SubScreen->AddMenuItemInput(81, "Board ID:", true); - SubScreen->AddMenuItemInput(82, "Board SN:", true); - SubScreen->AddMenuItemInput(83, "Board Type:", true); - SubScreen->AddMenuItemInput(84, "Board Version:", true); - SubScreen->AddMenuItemInput(85, "Chassis Type:", true); - SubScreen->AddMenuItemInput(86, "ROM Version:", true); - SubScreen->AddMenuItemInput(87, "ROM Release Date:", true); - SubScreen->AddMenuItemInput(62, "FirmwareFeatures:", true); - SubScreen->AddMenuItemInput(63, "FirmwareFeaturesMask:", true); - SubScreen->AddMenuItemInput(125, "ExtendedFirmwareFeatures:", true); - SubScreen->AddMenuItemInput(126, "ExtendedFirmwareFeaturesMask:", true); - SubScreen->AddMenuItemInput(17, "PlatformFeature:", true); - SubScreen->AddMenuItemInput(117, "EFI Version:", true); - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + mOpenCoreConfiguration.Booter.MmioWhitelist.Count = (UINT32)gSettings.Quirks.mmioWhiteListArray.size(); + mOpenCoreConfiguration.Booter.MmioWhitelist.AllocCount = mOpenCoreConfiguration.Booter.MmioWhitelist.Count; + mOpenCoreConfiguration.Booter.MmioWhitelist.ValueSize = sizeof(__typeof_am__(**mOpenCoreConfiguration.Booter.MmioWhitelist.Values)); // sizeof(OC_KERNEL_ADD_ENTRY) == 680 + if ( mOpenCoreConfiguration.Booter.MmioWhitelist.Count > 0 ) { + mOpenCoreConfiguration.Booter.MmioWhitelist.Values = (OC_BOOTER_WL_ENTRY**)AllocatePool(mOpenCoreConfiguration.Booter.MmioWhitelist.AllocCount * sizeof(*mOpenCoreConfiguration.Booter.MmioWhitelist.Values)); // sizeof(OC_KERNEL_ADD_ENTRY) == 680 + } else { + mOpenCoreConfiguration.Booter.MmioWhitelist.Values = NULL; + } + for ( size_t idx = 0 ; idx < gSettings.Quirks.mmioWhiteListArray.size() ; idx++ ) { + const SETTINGS_DATA::QuirksClass::MMIOWhiteList& entry = gSettings.Quirks.mmioWhiteListArray[idx]; + DBG("Bridge mmioWhiteList[%zu] to OC : comment=%s\n", idx, entry.comment.c_str()); + mOpenCoreConfiguration.Booter.MmioWhitelist.Values[idx] = (__typeof_am__(*mOpenCoreConfiguration.Booter.MmioWhitelist.Values))AllocatePool(mOpenCoreConfiguration.Booter.MmioWhitelist.ValueSize); + mOpenCoreConfiguration.Booter.MmioWhitelist.Values[idx]->Address = entry.address; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Booter.MmioWhitelist.Values[idx]->Comment, entry.comment.c_str()); + mOpenCoreConfiguration.Booter.MmioWhitelist.Values[idx]->Enabled = entry.enabled; + } + + // It's possible to memcpy the whole struct instead of assigning individual member. But that would be relying on internel C++ binary structure, + // and worse, if a field is added by OC, everything could be shifted. + memset(&mOpenCoreConfiguration.Booter.Quirks, 0, sizeof(mOpenCoreConfiguration.Booter.Quirks)); + mOpenCoreConfiguration.Booter.Quirks.AvoidRuntimeDefrag = gSettings.Quirks.OcBooterQuirks.AvoidRuntimeDefrag; + mOpenCoreConfiguration.Booter.Quirks.DevirtualiseMmio = gSettings.Quirks.OcBooterQuirks.DevirtualiseMmio; + mOpenCoreConfiguration.Booter.Quirks.DisableSingleUser = gSettings.Quirks.OcBooterQuirks.DisableSingleUser; + mOpenCoreConfiguration.Booter.Quirks.DisableVariableWrite = gSettings.Quirks.OcBooterQuirks.DisableVariableWrite; + mOpenCoreConfiguration.Booter.Quirks.DiscardHibernateMap = gSettings.Quirks.OcBooterQuirks.DiscardHibernateMap; + mOpenCoreConfiguration.Booter.Quirks.EnableSafeModeSlide = gSettings.Quirks.OcBooterQuirks.EnableSafeModeSlide; + mOpenCoreConfiguration.Booter.Quirks.EnableWriteUnprotector = gSettings.Quirks.OcBooterQuirks.EnableWriteUnprotector; + mOpenCoreConfiguration.Booter.Quirks.ForceExitBootServices = gSettings.Quirks.OcBooterQuirks.ForceExitBootServices; + mOpenCoreConfiguration.Booter.Quirks.ProtectMemoryRegions = gSettings.Quirks.OcBooterQuirks.ProtectMemoryRegions; + mOpenCoreConfiguration.Booter.Quirks.ProtectSecureBoot = gSettings.Quirks.OcBooterQuirks.ProtectSecureBoot; + mOpenCoreConfiguration.Booter.Quirks.ProtectUefiServices = gSettings.Quirks.OcBooterQuirks.ProtectUefiServices; + mOpenCoreConfiguration.Booter.Quirks.ProvideCustomSlide = gSettings.Quirks.OcBooterQuirks.ProvideCustomSlide; + mOpenCoreConfiguration.Booter.Quirks.ProvideMaxSlide = gSettings.Quirks.OcBooterQuirks.ProvideMaxSlide; + mOpenCoreConfiguration.Booter.Quirks.RebuildAppleMemoryMap = gSettings.Quirks.OcBooterQuirks.RebuildAppleMemoryMap; + mOpenCoreConfiguration.Booter.Quirks.ResizeAppleGpuBars = gSettings.Quirks.OcBooterQuirks.ResizeAppleGpuBars; + mOpenCoreConfiguration.Booter.Quirks.SetupVirtualMap = gSettings.Quirks.OcBooterQuirks.SetupVirtualMap; + mOpenCoreConfiguration.Booter.Quirks.SignalAppleOS = false; //gSettings.Quirks.OcBooterQuirks.SignalAppleOS; + mOpenCoreConfiguration.Booter.Quirks.SyncRuntimePermissions = gSettings.Quirks.OcBooterQuirks.SyncRuntimePermissions; + + + #endif + + + FillOCCpuInfo(&mOpenCoreCpuInfo); + + mOpenCoreConfiguration.Uefi.Quirks.TscSyncTimeout = gSettings.Quirks.OcBooterQuirks.TscSyncTimeout; + + #ifndef USE_OC_SECTION_Kernel + + XObjArray kextArray; + if (!DoHibernateWake) { + AddKextsInArray(&kextArray); + } + + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Scheme.KernelArch, "x86_64"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Scheme.KernelCache, gSettings.Quirks.OcKernelCache.c_str()); + mOpenCoreConfiguration.Kernel.Scheme.FuzzyMatch = gSettings.Quirks.FuzzyMatch; + + memset(&mOpenCoreConfiguration.Kernel.Quirks, 0, sizeof(mOpenCoreConfiguration.Kernel.Quirks)); + + mOpenCoreConfiguration.Kernel.Quirks.SetApfsTrimTimeout = -1; // Jief: Slice modified OcConfigurationLib.h to set -1 by default instead of 999. I prefer the modification here to minimize commits in OC submodule. Makes it easier to upgrade submodule. + mOpenCoreConfiguration.Kernel.Quirks.AppleCpuPmCfgLock = GlobalConfig.KPAppleIntelCPUPM || GlobalConfig.NeedPMfix ; + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmCfgLock = GlobalConfig.KPKernelPm || GlobalConfig.NeedPMfix ; + + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmExtraMsrs = gSettings.Quirks.OcKernelQuirks.AppleXcpmExtraMsrs; + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmForceBoost = gSettings.Quirks.OcKernelQuirks.AppleXcpmForceBoost; + #ifndef USE_OC_SECTION_PlatformInfo + mOpenCoreConfiguration.Kernel.Quirks.CustomSmbiosGuid = gSettings.KernelAndKextPatches.KPDELLSMBIOS; + #endif + mOpenCoreConfiguration.Kernel.Quirks.DisableIoMapper = gSettings.Quirks.OcKernelQuirks.DisableIoMapper; + mOpenCoreConfiguration.Kernel.Quirks.DisableLinkeditJettison = gSettings.Quirks.OcKernelQuirks.DisableLinkeditJettison; + mOpenCoreConfiguration.Kernel.Quirks.DisableRtcChecksum = gSettings.KernelAndKextPatches.KPAppleRTC; + mOpenCoreConfiguration.Kernel.Emulate.DummyPowerManagement = gSettings.Quirks.OcKernelQuirks.DummyPowerManagement; + mOpenCoreConfiguration.Kernel.Quirks.ExtendBTFeatureFlags = gSettings.Quirks.OcKernelQuirks.ExtendBTFeatureFlags; + mOpenCoreConfiguration.Kernel.Quirks.ExternalDiskIcons = gSettings.Quirks.OcKernelQuirks.ExternalDiskIcons; + mOpenCoreConfiguration.Kernel.Quirks.IncreasePciBarSize = gSettings.Quirks.OcKernelQuirks.IncreasePciBarSize; + mOpenCoreConfiguration.Kernel.Quirks.ForceAquantiaEthernet = gSettings.Quirks.OcKernelQuirks.ForceAquantiaEthernet; + mOpenCoreConfiguration.Kernel.Quirks.LapicKernelPanic = gSettings.KernelAndKextPatches.KPKernelLapic; + mOpenCoreConfiguration.Kernel.Quirks.PanicNoKextDump = gSettings.KernelAndKextPatches.KPPanicNoKextDump; + mOpenCoreConfiguration.Kernel.Quirks.PowerTimeoutKernelPanic = gSettings.Quirks.OcKernelQuirks.PowerTimeoutKernelPanic; + mOpenCoreConfiguration.Kernel.Quirks.ThirdPartyDrives = gSettings.Quirks.OcKernelQuirks.ThirdPartyDrives; + mOpenCoreConfiguration.Kernel.Quirks.XhciPortLimit = gSettings.Quirks.OcKernelQuirks.XhciPortLimit; + mOpenCoreConfiguration.Kernel.Quirks.ProvideCurrentCpuInfo = gSettings.Quirks.OcKernelQuirks.ProvideCurrentCpuInfo; + + mOpenCoreConfiguration.Kernel.Add.Count = (UINT32)kextArray.size(); + mOpenCoreConfiguration.Kernel.Add.AllocCount = mOpenCoreConfiguration.Kernel.Add.Count; + mOpenCoreConfiguration.Kernel.Add.ValueSize = sizeof(__typeof_am__(**mOpenCoreConfiguration.Kernel.Add.Values)); // sizeof(OC_KERNEL_ADD_ENTRY) == 680 + mOpenCoreConfiguration.Kernel.Add.Values = (OC_KERNEL_ADD_ENTRY**)malloc(mOpenCoreConfiguration.Kernel.Add.AllocCount*sizeof(*mOpenCoreConfiguration.Kernel.Add.Values)); // sizeof(OC_KERNEL_ADD_ENTRY*) == sizeof(ptr) + memset(mOpenCoreConfiguration.Kernel.Add.Values, 0, mOpenCoreConfiguration.Kernel.Add.AllocCount*sizeof(*mOpenCoreConfiguration.Kernel.Add.Values)); + + // Seems that Lilu must be first. + size_t pos = setKextAtPos(&kextArray, "Lilu.kext"_XS8, 0); + pos = setKextAtPos(&kextArray, "VirtualSMC.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "FakeSMC.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "WhateverGreen.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "AppleMCEReporterDisabler.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "AppleIntelI210Ethernet.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "USBWakeFixup.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "FeatureUnlock.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "vecLib.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "IOAudioFamily.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "IOSkywalkFamily.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "FakePCIID.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "FakePCIID_XHCIMux.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "AMDRyzenCPUPowerManagement.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "SMCAMDProcessor.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "AppleALC.kext"_XS8, pos); +// pos = setKextAtPos(&kextArray, "IntelMausi.kext"_XS8, pos); // not needed special order? + pos = setKextAtPos(&kextArray, "SMCProcessor.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "USBPorts.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooGPIO.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooI2CServices.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooI2C.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooI2CHID.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooSMBus.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "VoodooRMI.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "BrcmFirmwareData.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "BrcmPatchRAM2.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "BrcmPatchRAM3.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "IO80211FamilyLegacy.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "AirPortBrcmNIC.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "HS80211Family.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "corecaptureElCap.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "IO80211ElCap.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "AirPortAtheros40.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "SMCProcessorAMD.kext"_XS8, pos); + pos = setKextAtPos(&kextArray, "SMCSuperIO.kext"_XS8, pos); + + for (size_t kextIdx = 0 ; kextIdx < kextArray.size() ; kextIdx++ ) { + const SIDELOAD_KEXT& KextEntry = kextArray[kextIdx]; + DBG("Bridge kext to OC : Path=%ls\\%ls\n", KextEntry.KextDirNameUnderOEMPath.wc_str(), KextEntry.FileName.wc_str()); + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx] = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Add.Values))malloc(mOpenCoreConfiguration.Kernel.Add.ValueSize); + memset(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx], 0, mOpenCoreConfiguration.Kernel.Add.ValueSize); + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->Enabled = 1; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->Arch, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Scheme.KernelArch)); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->Comment, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->MaxKernel, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->MinKernel, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->Identifier, ""); + + assert( selfOem.isKextsDirFound() ); // be sure before calling getKextsPathRelToSelfDir() + XStringW dirPath = SWPrintf("%ls\\%ls", selfOem.getKextsDirPathRelToSelfDir().wc_str(), KextEntry.KextDirNameUnderOEMPath.wc_str()); + + XString8 bundleFullPath = S8Printf("%ls\\%ls", dirPath.wc_str(), KextEntry.FileName.wc_str()); + if ( FileExists(&self.getCloverDir(), bundleFullPath) ) { + XString8 bundlePathUnderKextsDir = S8Printf("%ls\\%ls", KextEntry.KextDirNameUnderOEMPath.wc_str(), KextEntry.FileName.wc_str()); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->BundlePath, bundlePathUnderKextsDir.c_str()); + // DBG("OC BundlePath = '%s'\n", OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->BundlePath)); + } else { + DBG("Cannot find kext bundlePath at '%s'\n", bundleFullPath.c_str()); + } + #if 1 + //CFBundleExecutable + XBool NoContents = false; + XStringW infoPlistPathRelToSelf = getKextPlist(&self.getCloverDir(), dirPath, KextEntry.FileName, &NoContents); //it will be fullPath, including dir + + // XBool inject = checkOSBundleRequired(dict); + XBool inject = true; + if (inject) { + if ( infoPlistPathRelToSelf.notEmpty()) { + if (NoContents) { + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistPath, "Info.plist"); + } else { + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistPath, "Contents\\Info.plist"); + } + // DBG("OC PlistPath = '%s'\n", OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistPath)); + } else { + DBG("Cannot find kext info.plist at '%ls'\n", KextEntry.FileName.wc_str()); + } + TagDict* dict = getInfoPlist(&self.getCloverDir(), infoPlistPathRelToSelf); + XString8 execpath = getKextExecPath(&self.getCloverDir(), KextEntry.KextDirNameUnderOEMPath, KextEntry.FileName, dict, NoContents); + if (execpath.notEmpty()) { + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->ExecutablePath, execpath.c_str()); + // DBG("OC ExecutablePath = '%s'\n", execpath.c_str()); + } + if ( dict ) dict->ReleaseTag(); + } + + #else + XStringW execpath = S8Printf("Contents\\MacOS\\%ls", KextEntry.FileName.subString(0, KextEntry.FileName.rindexOf(".")).wc_str()); + XStringW fullPath = SWPrintf("%s\\%ls", OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->BundlePath), execpath.wc_str()); + if ( FileExists(&self.getCloverDir(), fullPath) ) { + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->ExecutablePath, S8Printf("Contents\\MacOS\\%ls", KextEntry.FileName.subString(0, KextEntry.FileName.rindexOf(".")).wc_str()).c_str()); + } + XStringW infoPlistPathRelToSelf = SWPrintf("%s\\Contents\\Info.plist", OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->BundlePath)); + if (FileExists(&self.getCloverDir(), infoPlistPathRelToSelf)) { + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistPath, "Contents/Info.plist"); // TODO : is always Contents/Info.plist ? + } else { + DBG("Cannot find kext info.plist at '%ls'\n", infoPlistPathRelToSelf.wc_str()); + } + #endif + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->ImageData = NULL; + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->ImageDataSize = 0; + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistData = NULL; + mOpenCoreConfiguration.Kernel.Add.Values[kextIdx]->PlistDataSize = 0; + + } // for (size_t kextIdx + + + mOpenCoreConfiguration.Kernel.Force.Count = (UINT32)KernelAndKextPatches.ForceKextsToLoad.size(); + mOpenCoreConfiguration.Kernel.Force.AllocCount = mOpenCoreConfiguration.Kernel.Force.Count; + mOpenCoreConfiguration.Kernel.Force.ValueSize = sizeof(__typeof_am__(**mOpenCoreConfiguration.Kernel.Force.Values)); // sizeof(OC_KERNEL_FORCE_ENTRY) + int valuesSize = mOpenCoreConfiguration.Kernel.Force.AllocCount*sizeof(*mOpenCoreConfiguration.Kernel.Force.Values); + mOpenCoreConfiguration.Kernel.Force.Values = (OC_KERNEL_ADD_ENTRY**)malloc(valuesSize); // sizeof(OC_KERNEL_FORCE_ENTRY*) == sizeof(ptr) + memset(mOpenCoreConfiguration.Kernel.Force.Values, 0, valuesSize); + + + + for (size_t kextIdx = 0; kextIdx < KernelAndKextPatches.ForceKextsToLoad.size(); kextIdx++) { + const XStringW& forceKext = KernelAndKextPatches.ForceKextsToLoad[kextIdx]; + + DBG("Force kext to OC : Path=%ls\n", forceKext.wc_str()); + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx] = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Force.Values))malloc(mOpenCoreConfiguration.Kernel.Force.ValueSize); + memset(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx], 0, mOpenCoreConfiguration.Kernel.Force.ValueSize); + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->Enabled = 1; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->Arch, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Scheme.KernelArch)); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->Comment, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->MaxKernel, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->MinKernel, ""); + // OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->Identifier, ""); + + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->ImageData = NULL; + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->ImageDataSize = 0; + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->PlistData = NULL; + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->PlistDataSize = 0; + + REFIT_VOLUME * SystemVolume = Volume; + EFI_FILE* SysRoot = Volume->RootDir; + + + if (Volume->ApfsRole == APPLE_APFS_VOLUME_ROLE_PREBOOT) { + //search for other partition + DBG("boot from Preboot, index=%llu\n", Volume->Index); + size_t numbers = Volumes.size(); + size_t sysIndex = 0; + for (sysIndex=Volume->Index+1; sysIndex < numbers; sysIndex++) { + SystemVolume = &Volumes[sysIndex]; + SysRoot = SystemVolume->RootDir; + + DBG("test volume %zd, name %ls:\n", sysIndex, SystemVolume->VolName.wc_str()); + + if (FileExists(SysRoot, L"\\System\\Library\\CoreServices\\boot.efi")) { + DBG("boot.efi found on %zd\n", sysIndex); + } + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry = NULL; + DirIterOpen(SysRoot, L"\\System\\Library\\Extensions\\AMDSupport.kext\\Contents\\MacOS\\", &DirIter); + while (DirIterNext(&DirIter, 1, L"*", &DirEntry)) { + if (DirEntry->FileName[0] == '.') { + DBG("Skip dot entries: %ls\n", DirEntry->FileName); + continue; + } + DBG("%ls attr=%llu\n", DirEntry->FileName, DirEntry->Attribute); + } + DirIterClose(&DirIter); + if (FileExists(SysRoot, L"\\System\\Library\\Extensions\\AMDSupport.kext\\Contents\\MacOS\\AMDSupport")) { + DBG("AMDSupport found on %zd\n", sysIndex); //never found + break; + } + } + } + mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->ImageData = (UINT8*)SysRoot; + + size_t i1 = forceKext.rindexOf("\\") + 1; + size_t i2 = forceKext.rindexOf("."); + XStringW identifier = forceKext.subString(i1, i2 - i1); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->Identifier, S8Printf("%ls", identifier.wc_str()).c_str()); + + XString8 execpath = S8Printf("Contents\\MacOS\\%ls", identifier.wc_str()); + DBG("calculated execpath=%s\n", execpath.c_str()); + + + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->BundlePath, S8Printf("%ls",forceKext.wc_str()).c_str()); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->PlistPath, "Contents\\Info.plist"); + + //then we have to find executablePath and plistPath + DBG("bundle path=%s\n", mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->BundlePath.Value); + + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->ExecutablePath, execpath.c_str()); + DBG("assign executable as '%s'\n", mOpenCoreConfiguration.Kernel.Force.Values[kextIdx]->ExecutablePath.Value); + + } + if (gSettings.KernelAndKextPatches.BlockSkywalk) { + mOpenCoreConfiguration.Kernel.Block.Count = 1; + mOpenCoreConfiguration.Kernel.Block.AllocCount = 1; + mOpenCoreConfiguration.Kernel.Block.ValueSize = sizeof(__typeof_am__(**mOpenCoreConfiguration.Kernel.Block.Values)); + valuesSize = mOpenCoreConfiguration.Kernel.Block.AllocCount*sizeof(*mOpenCoreConfiguration.Kernel.Block.Values); + mOpenCoreConfiguration.Kernel.Block.Values = (OC_KERNEL_BLOCK_ENTRY**)malloc(valuesSize); + + memset(mOpenCoreConfiguration.Kernel.Block.Values, 0, valuesSize); + + mOpenCoreConfiguration.Kernel.Block.Values[0] = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Block.Values))malloc(mOpenCoreConfiguration.Kernel.Block.ValueSize); + memset(mOpenCoreConfiguration.Kernel.Block.Values[0], 0, mOpenCoreConfiguration.Kernel.Block.ValueSize); + mOpenCoreConfiguration.Kernel.Block.Values[0]->Enabled = 1; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->Arch, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Scheme.KernelArch)); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->Comment, "Allow IOSkywalk Downgrade"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->MaxKernel, ""); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->MinKernel, "23"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->Identifier, "com.apple.iokit.IOSkywalkFamily"); + OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[0]->Strategy, "Exclude"); + +// mOpenCoreConfiguration.Kernel.Block.Values[1] = (__typeof_am__(*mOpenCoreConfiguration.Kernel.Block.Values))malloc(mOpenCoreConfiguration.Kernel.Block.ValueSize); +// memset(mOpenCoreConfiguration.Kernel.Block.Values[1], 0, mOpenCoreConfiguration.Kernel.Block.ValueSize); +// mOpenCoreConfiguration.Kernel.Block.Values[1]->Enabled = 1; +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->Arch, OC_BLOB_GET(&mOpenCoreConfiguration.Kernel.Scheme.KernelArch)); +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->Comment, ""); +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->MaxKernel, ""); +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->MinKernel, "23"); +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->Identifier, "com.apple.driver.mDNSOffloadUserClient"); +// OC_STRING_ASSIGN(mOpenCoreConfiguration.Kernel.Block.Values[1]->Strategy, "Exclude"); + + } + #endif + + mOpenCoreConfiguration.Uefi.Output.ProvideConsoleGop = gSettings.GUI.ProvideConsoleGop; + OC_STRING_ASSIGN(mOpenCoreConfiguration.Uefi.Output.Resolution, XString8(gSettings.GUI.ScreenResolution).c_str()); + + if ( OpenRuntimeEfiName.notEmpty() ) { + XStringW FileName = SWPrintf("%ls\\%ls\\%ls", self.getCloverDirFullPath().wc_str(), getDriversPath().wc_str(), OpenRuntimeEfiName.wc_str()); + EFI_HANDLE DriverHandle; + Status = gBS->LoadImage(false, gImageHandle, FileDevicePath(self.getSelfLoadedImage().DeviceHandle, FileName), NULL, 0, &DriverHandle); + if ( !EFI_ERROR(Status) ) { + Status = gBS->StartImage(DriverHandle, 0, 0); + DBG("Start '%ls' : Status %s\n", OpenRuntimeEfiName.wc_str(), efiStrError(Status)); + + if ( !EFI_ERROR(Status) ) + { + OC_FIRMWARE_RUNTIME_PROTOCOL *FwRuntime; + Status = gBS->LocateProtocol ( + gOcFirmwareRuntimeProtocolGuid, + NULL, + (VOID **) &FwRuntime + ); + + if (!EFI_ERROR (Status)) { + if (FwRuntime->Revision == OC_FIRMWARE_RUNTIME_REVISION) { + } else { + DEBUG (( + DEBUG_ERROR, + "OCABC: Incompatible OpenRuntime r%u, require r%u\n", + (UINT32) FwRuntime->Revision, + (UINT32) OC_FIRMWARE_RUNTIME_REVISION + )); + DBG("Incompatible OpenRuntime r%llu, require r%u\n", FwRuntime->Revision, OC_FIRMWARE_RUNTIME_REVISION); + } + } + } + }else{ + DBG("Error when loading '%ls' : Status %s.\n", OpenRuntimeEfiName.wc_str(), efiStrError(Status)); + } + }else{ + DBG("No OpenRuntime driver. This is wrong, OpenRuntime is mandatory.\n"); + } + + OcMain(&mOpenCoreStorage, NULL); + + XStringW DevicePathAsString = DevicePathToXStringW(DevicePath); + if ( DevicePathAsString.rindexOf(".dmg") == MAX_XSIZE ) + { + // point to InternalEfiLoadImage from OC + Status = gBS->LoadImage ( + false, + gImageHandle, + DevicePath, + NULL, + 0, + &ImageHandle + ); + if ( EFI_ERROR(Status) ) { + DBG("LoadImage at '%ls' failed. Status = %s\n", DevicePathAsString.wc_str(), efiStrError(Status)); + return; + } + DBG("ImageHandle = %llx\n", uintptr_t(ImageHandle)); + } else { + // NOTE : OpenCore ignore the name of the dmg. + // InternalLoadDmg calls InternalFindFirstDmgFileName to find the dmg file name. + // So be careful that, if an other dmg exists in the dir, that might boot on the wrong one. + + EFI_DEVICE_PATH_PROTOCOL* DevicePathCopy = DuplicateDevicePath(DevicePath); + + EFI_DEVICE_PATH_PROTOCOL* PreviousNode = NULL; + EFI_DEVICE_PATH_PROTOCOL* Node = DevicePathCopy; + while (!IsDevicePathEnd(Node)) { + if ( Node->Type == MEDIA_DEVICE_PATH && Node->SubType == MEDIA_FILEPATH_DP ) { + PreviousNode = Node; + break; + } + + PreviousNode = Node; + Node = NextDevicePathNode(Node); + } + SetDevicePathEndNode(PreviousNode); + + EFI_DEVICE_PATH_PROTOCOL* LoaderPathBasenameNode = ConvertTextToDeviceNode(LoaderPath.dirname().wc_str()); + EFI_DEVICE_PATH_PROTOCOL* DevicePathToDmgDir = AppendDevicePathNode(DevicePathCopy, LoaderPathBasenameNode); + DBG("DevicePathToDmgDir = %ls\n", DevicePathToXStringW(DevicePathToDmgDir).wc_str()); + + INTERNAL_DMG_LOAD_CONTEXT DmgLoadContext = {0,0,0}; + DmgLoadContext.DevicePath = DevicePathToDmgDir; + EFI_DEVICE_PATH_PROTOCOL* BootEfiFromDmgDevicePath = InternalLoadDmg(&DmgLoadContext, OcDmgLoadingAnyImage); + DBG("DevicePath of dmg = %ls\n", DevicePathToXStringW(BootEfiFromDmgDevicePath).wc_str()); + + // point to InternalEfiLoadImage from OC + Status = gBS->LoadImage ( + false, + gImageHandle, + BootEfiFromDmgDevicePath, + NULL, + 0, + &ImageHandle + ); + if ( EFI_ERROR(Status) ) { + DBG("LoadImage at '%ls' failed. Status = %s\n", DevicePathToXStringW(BootEfiFromDmgDevicePath).wc_str(), efiStrError(Status)); + return; + } + } + + EFI_STATUS OptionalStatus = gBS->HandleProtocol ( + ImageHandle, + &gEfiLoadedImageProtocolGuid, + (void **) &LoadedImage + ); + if ( EFI_ERROR(OptionalStatus) ) return; // TODO message ? + } else { + // Load image into memory (will be started later) + Status = LoadEFIImage(DevicePath, LoaderPath.basename(), NULL, &ImageHandle); + if (EFI_ERROR(Status)) { + DBG("Image is not loaded, status=%s\n", efiStrError(Status)); + return; // no reason to continue if loading image failed + } + } + + egClearScreen(&BootBgColor); //if not set then it is already MenuBackgroundPixel + +// KillMouse(); + +// if (LoaderType == OSTYPE_OSX) { + if (OSTYPE_IS_OSX(LoaderType) || + OSTYPE_IS_OSX_RECOVERY(LoaderType) || + OSTYPE_IS_OSX_INSTALLER(LoaderType)) { + + // To display progress bar properly (especially in FV2 mode) boot.efi needs to be in graphics mode. + // Unfortunately many UEFI implementations change the resolution when SetMode happens. + // This is not what boot.efi expects, and it freely calls SetMode at its will. + // As a result we see progress bar at improper resolution and the background is also missing (10.12.x+). + // + // libeg already has a workaround for SetMode behaviour, so we extend it for boot.efi support. + // The approach tries to be follows: + // 1. Ensure we have graphics mode set (since it is a must in the future). + // 2. Request text mode for boot.efi, which it expects by default (here a SetMode libeg hack will trigger + // on problematic UEFI implementations like AMI). + egSetGraphicsModeEnabled(true); + egSetGraphicsModeEnabled(false); + + DBG("GetOSVersion:"); + + //needed for boot.efi patcher + Status = gBS->HandleProtocol(ImageHandle, &gEfiLoadedImageProtocolGuid, (void **) &LoadedImage); + // Correct OSVersion if it was not found + // This should happen only for 10.7-10.9 OSTYPE_OSX_INSTALLER + // For these cases, take OSVersion from loaded boot.efi image in memory + if ( macOSVersion.isEmpty()) { + + if (!EFI_ERROR(Status)) { + // version in boot.efi appears as "Mac OS X 10.?" + /* + Start OSName Mac OS X 10.12 End OSName Start OSVendor Apple Inc. End + */ + + InstallerVersion = AsciiStrStr((CHAR8*)LoadedImage->ImageBase, "Mac OS X "); + int location = 9; + if (InstallerVersion == NULL) { + InstallerVersion = AsciiStrStr((CHAR8*)LoadedImage->ImageBase, "macOS "); + location = 7; + } + if (InstallerVersion != NULL) { // string was found + InstallerVersion += location; // advance to version location + + if (strncmp(InstallerVersion, "10.7", 4) && + strncmp(InstallerVersion, "10.8", 4) && + strncmp(InstallerVersion, "10.9", 4) && + strncmp(InstallerVersion, "10.10", 5) && + strncmp(InstallerVersion, "10.11", 5) && + strncmp(InstallerVersion, "10.12", 5) && + strncmp(InstallerVersion, "10.13", 5) && + strncmp(InstallerVersion, "10.14", 5) && + strncmp(InstallerVersion, "10.15", 5) && + strncmp(InstallerVersion, "10.16", 5) && + strncmp(InstallerVersion, "11.", 3) && + strncmp(InstallerVersion, "12.", 3) && + strncmp(InstallerVersion, "13.", 3) && + strncmp(InstallerVersion, "14.", 3) && + strncmp(InstallerVersion, "15.", 3) + ) { + InstallerVersion = NULL; // flag known version was not found + } + if (InstallerVersion != NULL) { // known version was found in image + macOSVersion = InstallerVersion; + DBG("Corrected OSVersion: %s\n", macOSVersion.asString().c_str()); + } + } + } + BuildVersion.setEmpty(); + } + + if (BuildVersion.notEmpty()) { + DBG(" %s (%s)\n", macOSVersion.asString().c_str(), BuildVersion.c_str()); + } else { + DBG(" %s\n", macOSVersion.asString().c_str()); + } + + if ( macOSVersion >= MacOsVersion("10.11"_XS8) ) { + if (OSFLAG_ISSET(Flags, OSFLAG_NOSIP)) { + gSettings.RtVariables.CsrActiveConfig = (UINT32)0xBEF; + gSettings.RtVariables.BooterConfig = 0x28; + } + } + + FilterKextPatches(); + FilterKernelPatches(); + FilterBootPatches(); + if (LoadedImage && !BooterPatch((UINT8*)LoadedImage->ImageBase, LoadedImage->ImageSize)) { + DBG("Will not patch boot.efi\n"); + } + gConf.ReloadSmbios(OSName); + DelegateKernelPatches(); + + // Set boot argument for kernel if no caches, this should force kernel loading + if ( OSFLAG_ISSET(Flags, OSFLAG_NOCACHES) && !LoadOptions.containsStartWithIC("Kernel=") ) { + XString8 KernelLocation; + + if ( macOSVersion.notEmpty() && macOSVersion <= MacOsVersion("10.9"_XS8) ) { + KernelLocation.S8Printf("\"Kernel=/mach_kernel\""); + } else { + // used for 10.10, 10.11, and new version. Jief : also for unknown version. + KernelLocation.S8Printf("\"Kernel=/System/Library/Kernels/kernel\""); + } + LoadOptions.AddID(KernelLocation); + } + + // first patchACPI and find PCIROOT and RTC + // but before ACPI patch we need smbios patch + CheckEmptyFB(); + + + SmbiosFillPatchingValues(GlobalConfig.SetTable132, GlobalConfig.EnabledCores, g_SmbiosDiscoveredSettings.RamSlotCount, gConf.SlotDeviceArray, gSettings, gCPUStructure, &g_SmbiosInjectedSettings); + PatchSmbios(g_SmbiosInjectedSettings); + +#ifdef USE_OC_SECTION_Acpi + // If we use the ACPI section form config-oc.plist, let's also delegate the acpi patching to OC +#else + PatchACPI(Volume, macOSVersion); +#endif + +#ifdef JIEF_DEBUG + //SaveOemTables(); +#endif +// + + DbgHeader("RestSetup macOS"); + SetDevices(this); + SetVariablesForOSX(this); +// Jief : if we want to use our FixUSBOwnership, we need our OnExitBootServices + EventsInitialize(this); + FinalizeSmbios(g_SmbiosInjectedSettings); + + SetCPUProperties(); //very special procedure + + if (OSFLAG_ISSET(Flags, OSFLAG_HIBERNATED)) { + DoHibernateWake = PrepareHibernation(Volume); + } + SetupDataForOSX(DoHibernateWake); + + + if ( gDriversFlags.AptioFixLoaded && + !DoHibernateWake && + !LoadOptions.containsStartWithIC("slide=") ) { + // Add slide=0 argument for ML+ if not present + LoadOptions.AddID("slide=0"_XS8); + } + + + /** + * syscl - append "-xcpm" argument conditionally if set KernelXCPM on Intel Haswell+ low-end CPUs + */ + if (KernelAndKextPatches.KPKernelXCPM && + gCPUStructure.Vendor == CPU_VENDOR_INTEL && gCPUStructure.Model >= CPU_MODEL_HASWELL && + (gCPUStructure.BrandString.contains("Celeron") || gCPUStructure.BrandString.contains("Pentium")) && + macOSVersion >= MacOsVersion("10.8.5"_XS8) && macOSVersion < MacOsVersion("10.12"_XS8) && + (!LoadOptions.containsIC("-xcpm"))) { + // add "-xcpm" argv if not present on Haswell+ Celeron/Pentium + LoadOptions.AddID("-xcpm"_XS8); + } + + // add -xcpm on Ivy Bridge if set KernelXCPM and system version is 10.8.5 - 10.11.x + if (KernelAndKextPatches.KPKernelXCPM && + gCPUStructure.Model == CPU_MODEL_IVY_BRIDGE && + macOSVersion >= MacOsVersion("10.8.5"_XS8) && macOSVersion < MacOsVersion("10.12"_XS8) && + (!LoadOptions.containsIC("-xcpm"))) { + // add "-xcpm" argv if not present on Ivy Bridge + LoadOptions.AddID("-xcpm"_XS8); + } + + if (AudioIo) { + AudioIo->StopPlayback(AudioIo); +// CheckSyncSound(true); + EFI_DRIVER_BINDING_PROTOCOL *DriverBinding = NULL; + Status = gBS->HandleProtocol(AudioDriverHandle, &gEfiDriverBindingProtocolGuid, (void **)&DriverBinding); + if (DriverBinding) { + DriverBinding->Stop(DriverBinding, AudioDriverHandle, 0, NULL); + } + } + + + // blocking boot.efi output if -v is not specified + // note: this blocks output even if -v is specified in + // /Library/Preferences/SystemConfiguration/com.apple.Boot.plist + // which is wrong + // apianti - only block console output if using graphics + // but don't block custom boot logo + if (LoadOptions.containsIC("-v")) { + Flags = OSFLAG_UNSET(Flags, OSFLAG_USEGRAPHICS); + } + } + else if (OSTYPE_IS_WINDOWS(LoaderType)) { + + if (AudioIo) { + AudioIo->StopPlayback(AudioIo); + } + + DBG("Closing events for Windows\n"); + gBS->CloseEvent (OnReadyToBootEvent); + gBS->CloseEvent (ExitBootServiceEvent); + gBS->CloseEvent (mSimpleFileSystemChangeEvent); + + + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + + PatchACPI_OtherOS(L"Windows", false); + + } + else if (OSTYPE_IS_LINUX(LoaderType) || (LoaderType == OSTYPE_LINEFI)) { + + DBG("Closing events for Linux\n"); + gBS->CloseEvent (OnReadyToBootEvent); + gBS->CloseEvent (ExitBootServiceEvent); + gBS->CloseEvent (mSimpleFileSystemChangeEvent); + + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + + PatchACPI_OtherOS(L"Linux", false); + } + + if (gSettings.Boot.LastBootedVolume) { + if ( APFSTargetUUID.notNull() ) { + // Jief : we need to LoaderPath. If not, GUI can't know which target was selected. + SetStartupDiskVolume(Volume, LoaderPath); + }else{ + // Jief : I'm not sure why NullXStringW was given if LoaderType == OSTYPE_OSX. + // Let's do it like it was before when not in case of APFSTargetUUID + SetStartupDiskVolume(Volume, LoaderType == OSTYPE_OSX ? NullXStringW : LoaderPath); + } + } else if (gSettings.Boot.DefaultVolume.notEmpty()) { + // DefaultVolume specified in Config.plist or in Boot Option + // we'll remove macOS Startup Disk vars which may be present if it is used + // to reboot into another volume + RemoveStartupDiskVolume(); + } +/* + { + // UINT32 machineSignature = 0; + EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE *FadtPointer = NULL; + EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs = NULL; + + // DBG("---dump hibernations data---\n"); + FadtPointer = GetFadt(); + if (FadtPointer != NULL) { + Facs = (EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE*)(UINTN)(FadtPointer->FirmwareCtrl); + + DBG(" Firmware wake address=%08lx\n", Facs->FirmwareWakingVector); + DBG(" Firmware wake 64 addr=%16llx\n", Facs->XFirmwareWakingVector); + DBG(" Hardware signature =%08lx\n", Facs->HardwareSignature); + DBG(" GlobalLock =%08lx\n", Facs->GlobalLock); + DBG(" Flags =%08lx\n", Facs->Flags); + DBG(" HS at offset 0x%08X\n", OFFSET_OF(EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE, HardwareSignature)); + // machineSignature = Facs->HardwareSignature; + } + } +*/ + + BeginExternalScreen(OSFLAG_ISSET(Flags, OSFLAG_USEGRAPHICS)/*, L"Booting OS"*/); + + if (!OSTYPE_IS_WINDOWS(LoaderType) && !OSTYPE_IS_LINUX(LoaderType)) { + if (OSFLAG_ISSET(Flags, OSFLAG_USEGRAPHICS)) { + // save orig OutputString and replace it with + // null implementation + ConOutOutputString = gST->ConOut->OutputString; + gST->ConOut->OutputString = NullConOutOutputString; + } + + // Initialize the boot screen + if (EFI_ERROR(Status = InitBootScreen(this))) { + if (Status != EFI_ABORTED) DBG("Failed to initialize custom boot screen: %s!\n", efiStrError(Status)); + } + else if (EFI_ERROR(Status = LockBootScreen())) { + DBG("Failed to lock custom boot screen: %s!\n", efiStrError(Status)); + } + } // !OSTYPE_IS_WINDOWS + + if (OSTYPE_IS_OSX(LoaderType) || + OSTYPE_IS_OSX_RECOVERY(LoaderType) || + OSTYPE_IS_OSX_INSTALLER(LoaderType)) { + + if (DoHibernateWake) { + DBG("Closing events for wake\n"); + gBS->CloseEvent (OnReadyToBootEvent); +// gBS->CloseEvent (ExitBootServiceEvent); // Jief : we don't need that anymore, if we continue to use OC onExtBootService event + gBS->CloseEvent (mSimpleFileSystemChangeEvent); + + // When doing hibernate wake, save to DataHub only up to initial size of log + SavePreBootLog = false; + } else { + // delete boot-switch-vars if exists + Status = gRT->SetVariable(L"boot-switch-vars", gEfiAppleBootGuid, + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, + 0, NULL); + DeleteNvramVariable(L"IOHibernateRTCVariables", gEfiAppleBootGuid); + DeleteNvramVariable(L"boot-image", gEfiAppleBootGuid); + + } + SetupBooterLog(!DoHibernateWake); + + XStringW LoadOptionsAsXStringW = SWPrintf("%ls %s ", Basename(LoaderPath.wc_str()), LoadOptions.ConcatAll(" "_XS8).c_str()); + LoadedImage->LoadOptions = (void*)LoadOptionsAsXStringW.wc_str(); + LoadedImage->LoadOptionsSize = (UINT32)LoadOptionsAsXStringW.sizeInBytesIncludingTerminator(); + + DBG("Kernel quirks\n"); + DBG("ACPCL %d AXCL %d AXEM %d AXFB %d CSG %d DIM %d DLJ %d DRC %d DPM %d EBTFF %d EDI %d FAI %d IPBS %d LKP %d PNKD %d PTKP %d TPD %d XPL %d PCC %d\n", + mOpenCoreConfiguration.Kernel.Quirks.AppleCpuPmCfgLock, + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmCfgLock, + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmExtraMsrs, + mOpenCoreConfiguration.Kernel.Quirks.AppleXcpmForceBoost, + mOpenCoreConfiguration.Kernel.Quirks.CustomSmbiosGuid, + mOpenCoreConfiguration.Kernel.Quirks.DisableIoMapper, + mOpenCoreConfiguration.Kernel.Quirks.DisableLinkeditJettison, + mOpenCoreConfiguration.Kernel.Quirks.DisableRtcChecksum, + mOpenCoreConfiguration.Kernel.Emulate.DummyPowerManagement, + mOpenCoreConfiguration.Kernel.Quirks.ExtendBTFeatureFlags, + mOpenCoreConfiguration.Kernel.Quirks.ExternalDiskIcons, + mOpenCoreConfiguration.Kernel.Quirks.IncreasePciBarSize, + mOpenCoreConfiguration.Kernel.Quirks.ForceAquantiaEthernet, + mOpenCoreConfiguration.Kernel.Quirks.LapicKernelPanic, + mOpenCoreConfiguration.Kernel.Quirks.PanicNoKextDump, + mOpenCoreConfiguration.Kernel.Quirks.PowerTimeoutKernelPanic, + mOpenCoreConfiguration.Kernel.Quirks.ThirdPartyDrives, + mOpenCoreConfiguration.Kernel.Quirks.XhciPortLimit, + mOpenCoreConfiguration.Kernel.Quirks.ProvideCurrentCpuInfo); + + + DBG("Closing log\n"); + if (SavePreBootLog) { + Status = SaveBooterLog(&self.getCloverDir(), PREBOOT_LOG); + } + AllocSmallBlocks(); // shrink memory map; + +#ifdef JIEF_DEBUG + PrintMemoryMap(); + displayFreeMemory("Just before launching image"_XS8); +#endif + Status = gBS->StartImage (ImageHandle, 0, NULL); // point to OcStartImage from OC + + if ( EFI_ERROR(Status) ) { + // Ideally, we would return to the menu, displaying an error message + // Truth is that we get a black screen before seeing the menu again. + // If I remember well, we get a freeze in BdsLibConnectAllEfi() + // I'm guessing there is a lot of patching done for booting. + // To be able to go back to the menu and boot another thing, + // we must undo all the patching... + // Here is a quick, not as bad as a black screen solution : a text message and a reboot ! + DBG("StartImage failed : %s\n", efiStrError(Status)); + SaveBooterLog(&self.getCloverDir(), PREBOOT_LOG); + egSetGraphicsModeEnabled(false); + printf("StartImage failed : %s\n", efiStrError(Status)); + PauseForKey("Reboot needed."_XS8); + // Attempt warm reboot + gRT->ResetSystem(EfiResetWarm, EFI_SUCCESS, 0, NULL); + // Warm reboot may not be supported attempt cold reboot + gRT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); + // Terminate the screen and just exit + + return; + } + +}else{ + + StartEFILoadedImage(ImageHandle, LoadOptions, NullXStringW, LoaderPath.basename(), NULL); +} + // Unlock boot screen + if (EFI_ERROR(Status = UnlockBootScreen())) { + DBG("Failed to unlock custom boot screen: %s!\n", efiStrError(Status)); + } + if (OSFLAG_ISSET(Flags, OSFLAG_USEGRAPHICS)) { + // return back orig OutputString + gST->ConOut->OutputString = ConOutOutputString; + } + + + FinishExternalScreen(); + +} + + +void LEGACY_ENTRY::StartLegacy() +{ + EFI_STATUS Status = EFI_UNSUPPORTED; + + // Unload EmuVariable before booting legacy. + // This is not needed in most cases, but it seems to interfere with legacy OS + // booted on some UEFI bioses, such as Phoenix UEFI 2.0 + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + + if (gSettings.Boot.LastBootedVolume) { + SetStartupDiskVolume(Volume, NullXStringW); + } else if (gSettings.Boot.DefaultVolume.notEmpty()) { + // DefaultVolume specified in Config.plist: + // we'll remove macOS Startup Disk vars which may be present if it is used + // to reboot into another volume + RemoveStartupDiskVolume(); + } + + + egClearScreen(&MenuBackgroundPixel); + BeginExternalScreen(true/*, L"Booting Legacy OS"*/); + XImage BootLogoX; + BootLogoX.LoadXImage(&ThemeX->getThemeDir(), Volume->LegacyOS.IconName); + BootLogoX.Draw((UGAWidth - BootLogoX.GetWidth()) >> 1, + (UGAHeight - BootLogoX.GetHeight()) >> 1); + + //try my LegacyBoot + switch (Volume->BootType) { + case BOOTING_BY_CD: + Status = bootElTorito(Volume); + break; + case BOOTING_BY_MBR: + Status = bootMBR(Volume); + break; + case BOOTING_BY_PBR: + if (gSettings.Boot.LegacyBoot == "LegacyBiosDefault"_XS8) { + Status = bootLegacyBiosDefault(gSettings.Boot.LegacyBiosDefaultEntry); + } else if (gSettings.Boot.LegacyBoot == "PBRtest"_XS8) { + Status = bootPBRtest(Volume); + } else if (gSettings.Boot.LegacyBoot == "PBRsata"_XS8) { + Status = bootPBR(Volume, true); + } else { + // default + Status = bootPBR(Volume, false); + } + break; + default: + break; + } + CheckError(Status, L"while LegacyBoot"); + + FinishExternalScreen(); +} + +// +// pre-boot tool functions +// + +void REFIT_MENU_ENTRY_LOADER_TOOL::StartTool() +{ + DBG("Start Tool: %ls\n", LoaderPath.wc_str()); + egClearScreen(&MenuBackgroundPixel); + // assumes "Start " as assigned below + BeginExternalScreen(OSFLAG_ISSET(Flags, OSFLAG_USEGRAPHICS)/*, &Entry->Title[6]*/); // Shouldn't we check that length of Title is at least 6 ? + StartEFIImage(DevicePath, LoadOptions, NullXStringW, LoaderPath.basename(), NULL, NULL); + FinishExternalScreen(); +} + +// +// pre-boot driver functions +// + +static void ScanDriverDir(IN CONST CHAR16 *Path, OUT EFI_HANDLE **DriversToConnect, OUT UINTN *DriversToConnectNum) +{ + EFI_STATUS Status; + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry; + EFI_HANDLE DriverHandle; + EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; + UINTN DriversArrSize; + UINTN DriversArrNum; + EFI_HANDLE *DriversArr; + XBool Skip; + UINT8 AptioBlessed; + STATIC CHAR16 CONST * CONST AptioNames[] = { + L"AptioMemoryFix", + L"AptioFix3Drv", + L"AptioFix2Drv", + L"AptioFixDrv", + L"LowMemFix" + }; + STATIC UINT8 CONST AptioIndices[] = { + OFFSET_OF(DRIVERS_FLAGS, AptioMemFixLoaded), + OFFSET_OF(DRIVERS_FLAGS, AptioFix3Loaded), + OFFSET_OF(DRIVERS_FLAGS, AptioFix2Loaded), + OFFSET_OF(DRIVERS_FLAGS, AptioFixLoaded), + OFFSET_OF(DRIVERS_FLAGS, MemFixLoaded) + }; + + DriversArrSize = 0; + DriversArrNum = 0; + DriversArr = NULL; + // OpenRuntimeEfiName.setEmpty(); + +//only one driver with highest priority will obtain status "Loaded" + DirIterOpen(&self.getCloverDir(), Path, &DirIter); +#define BOOLEAN_AT_INDEX(k) (*(XBool*)((UINTN)&gDriversFlags + AptioIndices[(k)])) + for (size_t i = 0; i != ARRAY_SIZE(AptioIndices); ++i) + BOOLEAN_AT_INDEX(i) = false; + AptioBlessed = (UINT8) ARRAY_SIZE(AptioNames); + while (DirIterNext(&DirIter, 2, L"*.efi", &DirEntry)) { + size_t i; + for (i = 0; i != ARRAY_SIZE(AptioNames); ++i) + if (StrStr(DirEntry->FileName, AptioNames[i]) != NULL) + break; + if (((UINT8) i) >= AptioBlessed) + continue; + AptioBlessed = (UINT8) i; + if (!i) + break; + } + DirIterClose(&DirIter); + + // look through contents of the directory + DirIterOpen(&self.getCloverDir(), Path, &DirIter); + while (DirIterNext(&DirIter, 2, L"*.efi", &DirEntry)) { + Skip = (DirEntry->FileName[0] == L'.'); + for (size_t i=0; i<gSettings.DisabledDriverArray.size(); i++) { + if (StrStr(DirEntry->FileName, gSettings.DisabledDriverArray[i].wc_str()) != NULL) { + Skip = true; // skip this + break; + } + } + if (Skip) { + continue; + } + if ( LStringW(DirEntry->FileName).startWith("._") ) { + continue; + } + if ( LStringW(DirEntry->FileName).containsIC("OcQuirks") ) { + continue; + } + if ( LStringW(DirEntry->FileName).containsIC("AptioMemoryFix") ) { + continue; + } + + if ( LStringW(DirEntry->FileName).containsIC("OpenRuntime") ) { + if (!OpenRuntimeEfiName.isEmpty()) { + DBG(" - OpenRuntime already detected\n"); + continue; + } + if ( LStringW(DirEntry->FileName).isEqualIC("OpenRuntime-v12.efi") && LString8(OPEN_CORE_VERSION).isEqual("0.7.5") ) { + OpenRuntimeEfiName.takeValueFrom(DirEntry->FileName); + DBG(" - OpenRuntime-v12 for 075 taken from %ls\n", getDriversPath().wc_str()); + }else + if ( LStringW(DirEntry->FileName).isEqualIC("OpenRuntime-v12.efi") && LString8(OPEN_CORE_VERSION).isEqual("0.7.3") ) { + OpenRuntimeEfiName.takeValueFrom(DirEntry->FileName); + DBG(" - OpenRuntime-v12 for 073 taken from %ls\n", getDriversPath().wc_str()); + }else + if ( LStringW(DirEntry->FileName).isEqualIC("OpenRuntime-v11.efi") && LString8(OPEN_CORE_VERSION).isEqual("0.6.5") ) { + OpenRuntimeEfiName.takeValueFrom(DirEntry->FileName); + DBG(" - OpenRuntime-v11 for 065 taken from %ls\n", getDriversPath().wc_str()); + }else + if ( LStringW(DirEntry->FileName).isEqualIC("OpenRuntime-v11.efi") && LString8(OPEN_CORE_VERSION).isEqual("0.6.1") ) { + OpenRuntimeEfiName.takeValueFrom(DirEntry->FileName); + DBG(" - OpenRuntime-v11 for 061 taken from %ls\n", getDriversPath().wc_str()); + }else + if ( OpenRuntimeEfiName.isEmpty() ) { + OpenRuntimeEfiName.takeValueFrom(DirEntry->FileName); + } + continue; + } + { + size_t i; + // either AptioMem, AptioFix* or LowMemFix exclusively + for (i = 0; i != ARRAY_SIZE(AptioNames); ++i) + if (StrStr(DirEntry->FileName, AptioNames[i]) != NULL) + break; + if (i != ARRAY_SIZE(AptioNames)) { + if (((UINT8) i) != AptioBlessed) + continue; + if (AptioBlessed < (UINT8) ARRAY_SIZE(AptioIndices)) + BOOLEAN_AT_INDEX(AptioBlessed) = true; + AptioBlessed = (UINT8) ARRAY_SIZE(AptioNames); + } + } +#undef BOOLEAN_AT_INDEX + + XStringW FileName = SWPrintf("%ls\\%ls\\%ls", self.getCloverDirFullPath().wc_str(), Path, DirEntry->FileName); + Status = StartEFIImage(apd<EFI_DEVICE_PATH_PROTOCOL*>(FileDevicePath(self.getSelfLoadedImage().DeviceHandle, FileName)), NullXString8Array, LStringW(DirEntry->FileName), XStringW().takeValueFrom(DirEntry->FileName), NULL, &DriverHandle); + if (EFI_ERROR(Status)) { + continue; + } + if ( FileName.containsIC("AudioDxe") ) { + AudioDriverHandle = DriverHandle; + } + if ( FileName.containsIC("EmuVariable") ) { + gDriversFlags.EmuVariableLoaded = true; + } else if ( FileName.containsIC("Video") ) { + gDriversFlags.VideoLoaded = true; + } else if ( FileName.containsIC("Partition") ) { + gDriversFlags.PartitionLoaded = true; + } else if ( FileName.containsIC("HFS") ) { + gDriversFlags.HFSLoaded = true; + } else if ( FileName.containsIC("apfs") ) { + gDriversFlags.APFSLoaded = true; + } + if (DriverHandle != NULL && DriversToConnectNum != NULL && DriversToConnect != NULL) { + // driver loaded - check for EFI_DRIVER_BINDING_PROTOCOL + Status = gBS->HandleProtocol(DriverHandle, &gEfiDriverBindingProtocolGuid, (void **) &DriverBinding); + if (!EFI_ERROR(Status) && DriverBinding != NULL) { + DBG(" - driver needs connecting\n"); + // standard UEFI driver - we would reconnect after loading - add to array + MemoryStopRecord msr; // DriversArr won't be deallocated because it's passed to RegisterDriversToHighestPriority that keeps it global. + if (DriversArrSize == 0) { + // new array + DriversArrSize = 16; + DriversArr = (__typeof__(DriversArr))AllocateZeroPool(sizeof(EFI_HANDLE) * DriversArrSize); + } else if (DriversArrNum + 1 == DriversArrSize) { + // extend array + DriversArr = (__typeof__(DriversArr))ReallocatePool(DriversArrSize, DriversArrSize + 16, DriversArr); + DriversArrSize += 16; + } + DriversArr[DriversArrNum] = DriverHandle; + // DBG(" driver %ls included with Binding=%X\n", FileName, DriverBinding); + DriversArrNum++; + // we'll make array terminated + DriversArr[DriversArrNum] = NULL; + } + } + } + Status = DirIterClose(&DirIter); + if (Status != EFI_NOT_FOUND) { + CheckError(Status, SWPrintf( "while scanning the %ls directory", Path).wc_str()); + } + + if (DriversToConnectNum != NULL && DriversToConnect != NULL) { + *DriversToConnectNum = DriversArrNum; + *DriversToConnect = DriversArr; + } } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuChooseSmbios() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_MENU_SWITCH *InputBootArgs; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_CHOOSE_SMBIOS, NullXString8); - Entry->Title.SWPrintf("SMBIOS->"); - - SubScreen->AddMenuInfoLine_f("Select SMBIOS:"); - - for (UINTN i = 0; i < SmbiosList.size(); i++) { - InputBootArgs = new REFIT_MENU_SWITCH; - InputBootArgs->Title = SmbiosList[i]; - InputBootArgs->Row = i; - InputBootArgs->Item = &InputItems[65]; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - SubScreen->AddMenuEntry(SubMenuSmbios(), true); - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; +/** + * Some UEFI's (like HPQ EFI from HP notebooks) have DiskIo protocols + * opened BY_DRIVER (by Partition driver in HP case) even when no file system + * is produced from this DiskIo. This then blocks our FS drivers from connecting + * and producing file systems. + * To fix it: we will disconnect drivers that connected to DiskIo BY_DRIVER + * if this is partition volume and if those drivers did not produce file system. + */ +void DisconnectInvalidDiskIoChildDrivers(void) +{ + EFI_STATUS Status; + UINTN HandleCount = 0; + UINTN Index; + UINTN OpenInfoIndex; + EFI_HANDLE *Handles = NULL; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo; + UINTN OpenInfoCount; + XBool Found; + + DBG("Searching for invalid DiskIo BY_DRIVER connects:"); + + // + // Get all DiskIo handles + // + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiDiskIoProtocolGuid, NULL, &HandleCount, &Handles); + if (EFI_ERROR(Status) || HandleCount == 0) { + DBG(" no DiskIo handles\n"); + return; + } + + // + // Check every DiskIo handle + // + Found = false; + for (Index = 0; Index < HandleCount; Index++) { + //DBG("\n"); + //DBG(" - Handle %p:", Handles[Index]); + // + // If this is not partition - skip it. + // This is then whole disk and DiskIo + // should be opened here BY_DRIVER by Partition driver + // to produce partition volumes. + // + Status = gBS->HandleProtocol ( + Handles[Index], + &gEfiBlockIoProtocolGuid, + (void **) &BlockIo + ); + if (EFI_ERROR(Status)) { + //DBG(" BlockIo: %s - skipping\n", efiStrError(Status)); + continue; + } + if (BlockIo->Media == NULL) { + //DBG(" BlockIo: no media - skipping\n"); + continue; + + } + if (!BlockIo->Media->LogicalPartition) { + //DBG(" BlockIo: whole disk - skipping\n"); + continue; + + } + //DBG(" BlockIo: partition"); + + // + // If SimpleFileSystem is already produced - skip it, this is ok + // + Status = gBS->HandleProtocol ( + Handles[Index], + &gEfiSimpleFileSystemProtocolGuid, + (void **) &Fs + ); + if (Status == EFI_SUCCESS) { + //DBG(" FS: ok - skipping\n"); + continue; + } + //DBG(" FS: no"); + + // + // If no SimpleFileSystem on this handle but DiskIo is opened BY_DRIVER + // then disconnect this connection + // + Status = gBS->OpenProtocolInformation ( + Handles[Index], + &gEfiDiskIoProtocolGuid, + &OpenInfo, + &OpenInfoCount + ); + if (EFI_ERROR(Status)) { + //DBG(" OpenInfo: no - skipping\n"); + continue; + } + //DBG(" OpenInfo: %d", OpenInfoCount); + for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) { + if ((OpenInfo[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) == EFI_OPEN_PROTOCOL_BY_DRIVER) { + if (!Found) { + DBG("\n"); + } + Found = true; + Status = gBS->DisconnectController (Handles[Index], OpenInfo[OpenInfoIndex].AgentHandle, NULL); + //DBG(" BY_DRIVER Agent: %p, Disconnect: %s", OpenInfo[OpenInfoIndex].AgentHandle, efiStrError(Status)); + DBG(" - Handle %llx with DiskIo, is Partition, no Fs, BY_DRIVER Agent: %llx, Disconnect: %s\n", (uintptr_t)Handles[Index], (uintptr_t)(OpenInfo[OpenInfoIndex].AgentHandle), efiStrError(Status)); + } + } + gBS->FreePool(OpenInfo); // use gBS->FreePool instead of FreePool to avoid message from MemoryTracker + } + gBS->FreePool(Handles); // use gBS->FreePool instead of FreePool to avoid message from MemoryTracker + + if (!Found) { + DBG(" not found, all ok\n"); + } +} + +void DisconnectSomeDevices(void) +{ + EFI_STATUS Status; + UINTN HandleCount; + UINTN Index, Index2; + EFI_HANDLE *Handles ; + EFI_HANDLE *ControllerHandles; + UINTN ControllerHandleCount; + EFI_BLOCK_IO_PROTOCOL *BlockIo = NULL; +// EFI_DISK_IO_PROTOCOL *DiskIo = NULL; + EFI_PCI_IO_PROTOCOL *PciIo = NULL; +// EFI_FILE_PROTOCOL *RootFP = NULL; +// EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *VolumeFS = NULL; + PCI_TYPE00 Pci; + CHAR16 *DriverName = NULL; + EFI_COMPONENT_NAME_PROTOCOL *CompName = NULL; + + if (gDriversFlags.PartitionLoaded) { + DBG("Partition driver loaded: "); + // get all BlockIo handles + HandleCount = 0; + Handles = NULL; + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &HandleCount, &Handles); + if (Status == EFI_SUCCESS) { + for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->HandleProtocol(Handles[Index], &gEfiBlockIoProtocolGuid, (void **) &BlockIo); + if (EFI_ERROR(Status)) { + continue; + } + if (BlockIo->Media->BlockSize == 2048) { + // disconnect CD controller + Status = gBS->DisconnectController(Handles[Index], NULL, NULL); + DBG("CD disconnect %s", efiStrError(Status)); + } + } +/* for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->DisconnectController(Handles[Index], NULL, NULL); + } */ + FreePool(Handles); + } + DBG("\n"); + } + + if ((gDriversFlags.HFSLoaded) || (gDriversFlags.APFSLoaded)) { + if (gDriversFlags.HFSLoaded) { + DBG("HFS+ driver loaded\n"); + } + if (gDriversFlags.APFSLoaded) { + DBG("APFS driver loaded\n"); + } + + // get all FileSystem handles + ControllerHandleCount = 0; + ControllerHandles = NULL; + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &ControllerHandleCount, &ControllerHandles); + /* if (!EFI_ERROR(Status)) { + for (Index2 = 0; Index2 < ControllerHandleCount; Index2++) { + Status = gBS->DisconnectController(ControllerHandles[Index2], + NULL, NULL); + DBG("Driver [%d] disconnect %s\n", Index2, efiStrError(Status)); + } + } */ + + HandleCount = 0; + Handles = NULL; + + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiComponentNameProtocolGuid, NULL, &HandleCount, &Handles); + if (!EFI_ERROR(Status)) { + for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->OpenProtocol( + Handles[Index], + gEfiComponentNameProtocolGuid, + (void**)&CompName, + gImageHandle, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL); + + if (EFI_ERROR(Status)) { +// DBG("CompName %s\n", efiStrError(Status)); + continue; + } + // 2021-05, Jief : PG7 had a crash. In some cases, CompName->GetDriverName == NULL. + if ( CompName->GetDriverName == NULL ) { + DBG("DisconnectSomeDevices: GetDriverName CompName=%lld, CompName->GetDriverName=NULL\n", uintptr_t(CompName)); + continue; + } + Status = CompName->GetDriverName(CompName, "eng", &DriverName); + if (EFI_ERROR(Status)) { + continue; + } + if ((StriStr(DriverName, L"HFS")) || (StriStr(DriverName, L"apfs"))) { + for (Index2 = 0; Index2 < ControllerHandleCount; Index2++) { + Status = gBS->DisconnectController(ControllerHandles[Index2], + Handles[Index], NULL); + //DBG("Disconnect [%ls] from %llX: %s\n", DriverName, uintptr_t(ControllerHandles[Index2]), efiStrError(Status)); + } + } + } + gBS->FreePool(Handles); // use gBS->FreePool instead of FreePool to avoid message from MemoryTracker + } +// DBG("\n"); + gBS->FreePool(ControllerHandles); // use gBS->FreePool instead of FreePool to avoid message from MemoryTracker + } + + + if (gDriversFlags.VideoLoaded) { + DBG("Video driver loaded: "); + // get all PciIo handles + HandleCount = 0; + Handles = NULL; + Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiPciIoProtocolGuid, NULL, &HandleCount, &Handles); + if (Status == EFI_SUCCESS) { + for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->HandleProtocol(Handles[Index], &gEfiPciIoProtocolGuid, (void **) &PciIo); + if (EFI_ERROR(Status)) { + continue; + } + Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, 0, sizeof (Pci) / sizeof (UINT32), &Pci); + if (!EFI_ERROR(Status)) { + if(IS_PCI_VGA(&Pci) == true) { + // disconnect VGA + Status = gBS->DisconnectController(Handles[Index], NULL, NULL); + DBG("disconnect %s", efiStrError(Status)); + } + } + } + FreePool(Handles); + } + DBG("\n"); + } + + if (!gFirmwareClover) { + DisconnectInvalidDiskIoChildDrivers(); + } +} + + +void PatchVideoBios(UINT8 *Edid) +{ + + if ( gSettings.Graphics.PatchVBiosBytes.notEmpty() ) { + VideoBiosPatchBytes(gSettings.Graphics.PatchVBiosBytes.getVBIOS_PATCH_BYTES(), gSettings.Graphics.PatchVBiosBytes.getVBIOS_PATCH_BYTES_count()); + } + + if (gSettings.Graphics.PatchVBios) { + VideoBiosPatchNativeFromEdid(Edid); + } +} + + +static void LoadDrivers(void) +{ + EFI_STATUS Status; + EFI_HANDLE *DriversToConnect = NULL; + UINTN DriversToConnectNum = 0; + UINT8 *Edid; + UINTN VarSize = 0; + XBool VBiosPatchNeeded; + + DbgHeader("LoadDrivers"); + + // load drivers from /efi/drivers +#if defined(MDE_CPU_X64) + if (gFirmwareClover) { + if (FileExists(&self.getCloverDir(), L"drivers\\BIOS")) { + ScanDriverDir(L"drivers\\BIOS", &DriversToConnect, &DriversToConnectNum); + } else { + ScanDriverDir(L"drivers64", &DriversToConnect, &DriversToConnectNum); + } + } else { + OpenRuntimeEfiName.setEmpty(); + if (FileExists(&self.getCloverDir(), L"drivers\\5142")) { + ScanDriverDir(L"drivers\\5142", &DriversToConnect, &DriversToConnectNum); + } + if (FileExists(&self.getCloverDir(), L"drivers\\UEFI")) { + ScanDriverDir(L"drivers\\UEFI", &DriversToConnect, &DriversToConnectNum); + } else { + ScanDriverDir(L"drivers64UEFI", &DriversToConnect, &DriversToConnectNum); + } + } +#else + ScanDriverDir(L"drivers32", &DriversToConnect, &DriversToConnectNum); +#endif + // DriversToConnect is allocated by ScanDriverDir, but DO NOT free it. RegisterDriversToHighestPriority will store it in the global var mPriorityDrivers. + + VBiosPatchNeeded = gSettings.Graphics.PatchVBios || gSettings.Graphics.PatchVBiosBytes.getVBIOS_PATCH_BYTES_count() > 0; + if (VBiosPatchNeeded) { + // check if it is already done in CloverEFI BiosVideo + Status = gRT->GetVariable ( + L"CloverVBiosPatchDone", + gEfiGlobalVariableGuid, + NULL, + &VarSize, + NULL + ); + if (Status == EFI_BUFFER_TOO_SMALL) { + // var exists - it's done - let's not do it again + VBiosPatchNeeded = false; + } + } + + if ( (gSettings.Graphics.EDID.CustomEDID.notEmpty() && gFirmwareClover) || (VBiosPatchNeeded && !gDriversFlags.VideoLoaded)) { + // we have video bios patch - force video driver reconnect + DBG("Video bios patch requested or CustomEDID - forcing video reconnect\n"); + gDriversFlags.VideoLoaded = true; + DriversToConnectNum++; + } + + UninitRefitLib(); + if (DriversToConnectNum > 0) { + DBG("%llu drivers needs connecting ...\n", DriversToConnectNum); + // note: our platform driver protocol + // will use DriversToConnect - do not release it + RegisterDriversToHighestPriority(DriversToConnect); + if (VBiosPatchNeeded) { + if (gSettings.Graphics.EDID.CustomEDID.notEmpty()) { + Edid = gSettings.Graphics.EDID.CustomEDID.data(); + } else { + Edid = getCurrentEdid(); + } + DisconnectSomeDevices(); + PatchVideoBios(Edid); + if (gSettings.Graphics.EDID.CustomEDID.isEmpty()) { + FreePool(Edid); + } + } else { + DisconnectSomeDevices(); + } + BdsLibConnectAllDriversToAllControllers(); + + // Boot speedup: remove temporary "BiosVideoBlockSwitchMode" RT var + // to unlock mode switching in CsmVideo + gRT->SetVariable(L"BiosVideoBlockSwitchMode", gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS, 0, NULL); + }else{ + BdsLibConnectAllEfi(); // jief : without any driver loaded, i couldn't see my CD, unless I call BdsLibConnectAllEfi + } + ReinitRefitLib(); } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuDsdtFix() +INTN FindDefaultEntry(void) { - REFIT_MENU_ITEM_OPTIONS *Entry; //, *SubEntry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_DSDT, NullXString8); - - SubScreen->AddMenuCheck("Add DTGP", FIX_DTGP, 67); - SubScreen->AddMenuCheck("Fix Darwin as WinXP", FIX_WARNING, 67); - SubScreen->AddMenuCheck("Fix Darwin as Win7", FIX_DARWIN, 67); - SubScreen->AddMenuCheck("Fix shutdown", FIX_SHUTDOWN, 67); - SubScreen->AddMenuCheck("Add MCHC", FIX_MCHC, 67); - SubScreen->AddMenuCheck("Fix HPET", FIX_HPET, 67); - SubScreen->AddMenuCheck("Fake LPC", FIX_LPC, 67); - SubScreen->AddMenuCheck("Fix IPIC", FIX_IPIC, 67); - SubScreen->AddMenuCheck("Add SMBUS", FIX_SBUS, 67); - SubScreen->AddMenuCheck("Fix display", FIX_DISPLAY, 67); - SubScreen->AddMenuCheck("Fix IDE", FIX_IDE, 67); - SubScreen->AddMenuCheck("Fix SATA", FIX_SATA, 67); - SubScreen->AddMenuCheck("Fix Firewire", FIX_FIREWIRE, 67); - SubScreen->AddMenuCheck("Fix USB", FIX_USB, 67); - SubScreen->AddMenuCheck("Fix LAN", FIX_LAN, 67); - SubScreen->AddMenuCheck("Fix Airport", FIX_WIFI, 67); - SubScreen->AddMenuCheck("Fix sound", FIX_HDA, 67); - SubScreen->AddMenuCheck("Fix RTC", FIX_RTC, 67); - SubScreen->AddMenuCheck("Fix TMR", FIX_TMR, 67); - SubScreen->AddMenuCheck("Add IMEI", FIX_IMEI, 67); - SubScreen->AddMenuCheck("Fix IntelGFX", FIX_INTELGFX, 67); - SubScreen->AddMenuCheck("Fix _WAK", FIX_WAK, 67); - SubScreen->AddMenuCheck("Del unused", FIX_UNUSED, 67); - SubScreen->AddMenuCheck("Fix ADP1", FIX_ADP1, 67); - SubScreen->AddMenuCheck("Add PNLF", FIX_PNLF, 67); - SubScreen->AddMenuCheck("Fix S3D", FIX_S3D, 67); - SubScreen->AddMenuCheck("Rename ACST", FIX_ACST, 67); - SubScreen->AddMenuCheck("Add HDMI", FIX_HDMI, 67); - SubScreen->AddMenuCheck("Fix Regions", FIX_REGIONS, 67); - SubScreen->AddMenuCheck("Fix Mutex", FIX_MUTEX, 67); - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - ModifyTitles(Entry); - - return Entry; -} + INTN Index = -1; + REFIT_VOLUME *Volume; + XBool SearchForLoader; -REFIT_ABSTRACT_MENU_ENTRY* SubMenuDSDTPatches() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_INPUT_DIALOG *InputBootArgs; +// DBG("FindDefaultEntry ...\n"); + //DbgHeader("FindDefaultEntry"); + + if ( gSettings.Boot.BootFirstAvailable ) return 0; + + // + // try to detect volume set by Startup Disk or previous Clover selection + // with broken nvram this requires emulation to be installed. + // enable emulation to determine efi-boot-device-data + if (gEmuVariableControl != NULL) { + gEmuVariableControl->InstallEmulation(gEmuVariableControl); + } - size_t PatchDsdtNum = gSettings.ACPI.DSDT.DSDTPatchArray.size(); + Index = FindStartupDiskVolume(&MainMenu); - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_DSDT_PATCHES, "Custom DSDT patches->"_XS8); + if (Index >= 0) { + DBG("Boot redirected to Entry %lld. '%ls'\n", Index, MainMenu.Entries[Index].Title.s()); + // we got boot-device-data, no need to keep emulating anymore + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + return Index; + } + + // + // if not found, then try DefaultVolume from config.plist + // if not null or empty, search volume that matches gSettings.Boot.DefaultVolume + // + if (gSettings.Boot.DefaultVolume.notEmpty()) { + + // if not null or empty, also search for loader that matches gSettings.Boot.DefaultLoader + SearchForLoader = gSettings.Boot.DefaultLoader.notEmpty(); +/* + if (SearchForLoader) { + DBG("Searching for DefaultVolume '%ls', DefaultLoader '%ls' ...\n", gSettings.Boot.DefaultVolume, gSettings.Boot.DefaultLoader); + } else { + DBG("Searching for DefaultVolume '%ls' ...\n", gSettings.Boot.DefaultVolume); + } +*/ + for (Index = 0; Index < (INTN)MainMenu.Entries.size() && MainMenu.Entries[Index].getLOADER_ENTRY() && MainMenu.Entries[Index].getLOADER_ENTRY()->Row == 0 ; Index++) { + + LOADER_ENTRY& Entry = *MainMenu.Entries[Index].getLOADER_ENTRY(); + if (!Entry.Volume) { + continue; + } + + Volume = Entry.Volume; + if ( (Volume->VolName.isEmpty() || Volume->VolName != gSettings.Boot.DefaultVolume) && + !Volume->DevicePathString.contains(gSettings.Boot.DefaultVolume) ) { + continue; + } + + // we alreday know that Entry.isLoader + if (SearchForLoader && (/*Entry.Tag != TAG_LOADER ||*/ !Entry.LoaderPath.containsIC(gSettings.Boot.DefaultLoader))) { + continue; + } + + DBG(" - found entry %lld. '%ls', Volume '%ls', DevicePath '%ls'\n", Index, Entry.Title.s(), Volume->VolName.wc_str(), Entry.DevicePathString.wc_str()); + // if first method failed and second succeeded - uninstall emulation + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + return Index; + } - for (size_t Index = 0; Index < PatchDsdtNum; Index++) { - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf("%90s", gSettings.ACPI.DSDT.DSDTPatchArray[Index].PatchDsdtLabel.c_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &gSettings.ACPI.DSDT.DSDTPatchArray[Index].PatchDsdtMenuItem; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + DBG("Default boot entry not found\n"); + // if both methods to determine default boot entry have failed - uninstall emulation before GUI + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); + } + return -1; } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuDsdts() +void SetVariablesFromNvram() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_MENU_SWITCH *InputBootArgs; - UINTN i; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_ACPI, "Dsdt name->"_XS8); - - SubScreen->AddMenuInfoLine_f("Select a DSDT file:"); - SubScreen->AddMenuItemSwitch(116, "BIOS.aml", false); - - for (i = 0; i < DsdtsList.size(); i++) { - InputBootArgs = new REFIT_MENU_SWITCH; - InputBootArgs->Title.takeValueFrom(DsdtsList[i]); - InputBootArgs->Row = i + 1; - InputBootArgs->Item = &InputItems[116]; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + CHAR8 *tmpString; + UINTN Size = 0; + UINTN index = 0, index2, i; + CHAR8 *arg = NULL; + +// DbgHeader("SetVariablesFromNvram"); + + tmpString = (__typeof__(tmpString))GetNvramVariable(L"boot-args", gEfiAppleBootGuid, NULL, &Size); + if (tmpString && (Size <= 0x1000) && (Size > 0)) { + DBG("found boot-args in NVRAM:%s, size=%llu\n", tmpString, Size); + // use and forget old one +// DeleteNvramVariable(L"boot-args", &gEfiAppleBootGuid); + Size = AsciiStrLen(tmpString); // some EFI implementations include '\0' in Size, and others don't, so update Size to string length + arg = (__typeof__(arg))AllocatePool(Size+1); + +/* if (AsciiStrStr(tmpString, "nvda_drv=1")) { //found substring + gSettings.NvidiaWeb = true; + } */ + //first we will find new args that is not present in main args + index = 0; + while ((index < Size) && (tmpString[index] != 0x0)) { + ZeroMem(arg, Size+1); + index2 = 0; + if (tmpString[index] != '\"') { + // DBG("search space index=%d\n", index); + while ((index < Size) && (tmpString[index] != 0x20) && (tmpString[index] != 0x0)) { + arg[index2++] = tmpString[index++]; + } + DBG("...found arg:%s\n", arg); + } else { + index++; +// DBG("search quote index=%d\n", index); + while ((index < Size) && (tmpString[index] != '\"') && (tmpString[index] != 0x0)) { + arg[index2++] = tmpString[index++]; + } + if (tmpString[index] == '\"') { + index++; + } + DBG("...found quoted arg:\n"/*, arg*/); + } + while (tmpString[index] == 0x20) { + index++; + } + // For the moment only arg -s must be ignored + if (AsciiStrCmp(arg, "-s") == 0) { + DBG("...ignoring arg:%s\n", arg); + continue; + } + if (!gSettings.Boot.BootArgs.contains(arg)) { + //this arg is not present will add + DBG("...adding arg:%s\n", arg); + gSettings.Boot.BootArgs.trim(); + gSettings.Boot.BootArgs += ' '; + for (i = 0; i < index2; i++) { + gSettings.Boot.BootArgs += arg[i]; + } + gSettings.Boot.BootArgs += ' '; + } + } + FreePool(arg); + } + if (tmpString) { + FreePool(tmpString); + } + + tmpString = (__typeof__(tmpString))GetNvramVariable(L"nvda_drv", gEfiAppleBootGuid, NULL, NULL); + if (tmpString && AsciiStrCmp(tmpString, "1") == 0) { + gSettings.SystemParameters.NvidiaWeb = true; + } + if (tmpString) { + FreePool(tmpString); + } +} -REFIT_ABSTRACT_MENU_ENTRY* SubMenuACPI() +void +GetListOfConfigs() { - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry; - // create the entry in the options menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_ACPI, "ACPI patching->"_XS8); + ConfigsList.setEmpty(); + OldChosenConfig = 0; - // submenu description - SubScreen->AddMenuInfoLine_f("Choose options to patch ACPI"); + DirIterOpen(&selfOem.getConfigDir(), NULL, &DirIter); + DbgHeader("Found config plists"); + while (DirIterNext(&DirIter, 2, L"config*.plist", &DirEntry)) { + if (DirEntry->FileName[0] == L'.') { + continue; + } + if (StriCmp(DirEntry->FileName, L"config.plist") == 0) { + OldChosenConfig = ConfigsList.size(); // DirEntry->FileName is not yet inserted into ConfigsList. So its index will be ConfigsList.size() + } + size_t NameLen = wcslen(DirEntry->FileName) - 6; //without ".plist" + if ( NameLen <= MAX_INTN ) { + ConfigsList.AddReference(SWPrintf("%.*ls", (int)NameLen, DirEntry->FileName).forgetDataWithoutFreeing(), true); // this avoid to reallocate and copy memory + DBG("- %ls\n", DirEntry->FileName); + }else{ + DBG("- bug!, NameLen > MAX_INTN"); + } + } + DirIterClose(&DirIter); +} - SubScreen->AddMenuItemInput(102, "Debug DSDT", false); +void +GetListOfDsdts() +{ + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry; - SubScreen->AddMenuEntry(SubMenuDsdts(), true); - SubScreen->AddMenuEntry(SubMenuDropTables(), true); - SubScreen->AddMenuEntry(SubMenuDsdtFix(), true); - SubScreen->AddMenuEntry(SubMenuDSDTPatches(), true); - SubScreen->AddMenuItemInput(49, "Fix MCFG", false); - SubScreen->AddMenuItemInput(124, "Fix Headers", gSettings.ACPI.FixHeaders); + DsdtsList.setEmpty(); + OldChosenDsdt = 0xFFFF; - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + DirIterOpen(&selfOem.getConfigDir(), L"ACPI\\patched", &DirIter); + DbgHeader("Found DSDT tables"); + while (DirIterNext(&DirIter, 2, L"DSDT*.aml", &DirEntry)) { + if (DirEntry->FileName[0] == L'.') { + continue; + } + if ( gSettings.ACPI.DSDT.DsdtName.isEqualIC(DirEntry->FileName) ) { + OldChosenDsdt = DsdtsList.size(); // DirEntry->FileName is not yet inserted into DsdtsList. So its index will be DsdtsList.size() + } + size_t NameLen = wcslen(DirEntry->FileName); //with ".aml" + DsdtsList.AddReference(SWPrintf("%.*ls", (int)NameLen, DirEntry->FileName).forgetDataWithoutFreeing(), true); // this avoid to reallocate and copy memory + DBG("- %ls\n", DirEntry->FileName); + } + DirIterClose(&DirIter); } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuAudioPort() +void +GetListOfACPI() { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_MENU_SWITCH *InputBootArgs; - UINTN i; + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry = NULL; - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_AUDIOPORTS, "Startup sound output->"_XS8); +// XStringW AcpiPath = SWPrintf("%ls\\ACPI\\patched", OEMPath.wc_str()); +// DBG("Get list of ACPI at path %ls\n", AcpiPath.wc_str()); + ACPIPatchedAML.setEmpty(); + DirIterOpen(&selfOem.getConfigDir(), L"ACPI\\patched", &DirIter); - SubScreen->AddMenuInfoLine_f("Select an audio output, press F7 to test"); - SubScreen->AddMenuItemInput(120, "Volume:", true); - - for (i = 0; i < AudioList.size(); i++) { - InputBootArgs = new REFIT_MENU_SWITCH; - InputBootArgs->Title.SWPrintf("%ls_%s", AudioList[i].Name.wc_str(), AudioOutputNames[AudioList[i].Device]); - InputBootArgs->Row = i; - InputBootArgs->Item = &InputItems[119]; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } + while (DirIterNext(&DirIter, 2, L"*.aml", &DirEntry)) { +// DBG("next entry is %ls\n", DirEntry->FileName); + if (DirEntry->FileName[0] == L'.') { + continue; + } + if (StriStr(DirEntry->FileName, L"DSDT")) { + continue; + } +// DBG("Found name %ls\n", DirEntry->FileName); + XBool ACPIDisabled = false; + ACPI_PATCHED_AML* ACPIPatchedAMLTmp = new ACPI_PATCHED_AML; + ACPIPatchedAMLTmp->FileName.takeValueFrom(DirEntry->FileName); + + INTN Count = gSettings.ACPI.DisabledAML.size(); + for (INTN i = 0; i < Count; i++) { + if ( gSettings.ACPI.DisabledAML[i].isEqualIC(ACPIPatchedAMLTmp->FileName) ) { +// if ((gSettings.ACPI.DisabledAML[i] != NULL) && +// (StriCmp(ACPIPatchedAMLTmp->FileName, gSettings.ACPI.DisabledAML[i]) == 0) +// ) { + ACPIDisabled = true; + break; + } + } + ACPIPatchedAMLTmp->MenuItem.BValue = ACPIDisabled; + ACPIPatchedAML.AddReference(ACPIPatchedAMLTmp, true); + } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; + DirIterClose(&DirIter); } -void CreateMenuProps(REFIT_MENU_SCREEN* SubScreen, SETTINGS_DATA::DevicesClass::SimplePropertyClass* Prop) +void +GetListOfThemes () { - REFIT_INPUT_DIALOG *InputBootArgs; - - InputBootArgs = new REFIT_INPUT_DIALOG; - InputBootArgs->Title.SWPrintf(" key: %s", Prop->Key.c_str()); - InputBootArgs->Row = 0xFFFF; //cursor - InputBootArgs->Item = &Prop->MenuItem; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - switch (Prop->ValueType) { - case kTagTypeInteger: - SubScreen->AddMenuInfo_f(" value: 0x%08llx", *(UINT64*)Prop->Value.data()); - break; - case kTagTypeString: - SubScreen->AddMenuInfo_f(" value: %90s", Prop->Value.data()); - break; - case kTagTypeFalse: - SubScreen->AddMenuInfo_f((" value: false")); - break; - case kTagTypeTrue: - SubScreen->AddMenuInfo_f((" value: true")); - break; - case kTagTypeFloat: - SubScreen->AddMenuInfo_f(" value: %f", *(float*)Prop->Value.data()); - break; - default: //type data, print first 24 bytes - SubScreen->AddMenuInfo_f(" value[%zu]: %24s", Prop->Value.size(), Bytes2HexStr((UINT8*)Prop->Value.data(), MIN(24, Prop->Value.size())).c_str()); - break; - } + EFI_STATUS Status = EFI_NOT_FOUND; + REFIT_DIR_ITER DirIter; + EFI_FILE_INFO *DirEntry; + XStringW ThemeTestPath; + EFI_FILE *ThemeTestDir = NULL; + UINT8 *ThemePtr = NULL; + UINTN Size = 0; + + DbgHeader("GetListOfThemes"); + + ThemeNameArray.setEmpty(); + if ( !self.themesDirExists() ) { + DBG("No theme dir was discovered\n"); + return; + } + DirIterOpen(&self.getThemesDir(), NULL, &DirIter); + while (DirIterNext(&DirIter, 1, L"*", &DirEntry)) { + if (DirEntry->FileName[0] == '.') { + //DBG("Skip theme: %ls\n", DirEntry->FileName); + continue; + } + //DBG("Found theme directory: %ls", DirEntry->FileName); + DBG("- [%02zu]: %ls", ThemeNameArray.size(), DirEntry->FileName); + Status = self.getThemesDir().Open(&self.getThemesDir(), &ThemeTestDir, DirEntry->FileName, EFI_FILE_MODE_READ, 0); + if (!EFI_ERROR(Status)) { + Status = egLoadFile(ThemeTestDir, CONFIG_THEME_FILENAME, &ThemePtr, &Size); + if (EFI_ERROR(Status) || (ThemePtr == NULL) || (Size == 0)) { + Status = egLoadFile(ThemeTestDir, CONFIG_THEME_SVG, &ThemePtr, &Size); + if (EFI_ERROR(Status)) { + Status = EFI_NOT_FOUND; + DBG(" - bad theme because %ls nor %ls can't be load", CONFIG_THEME_FILENAME, CONFIG_THEME_SVG); + } + } + if (!EFI_ERROR(Status)) { + //we found a theme + if ((StriCmp(DirEntry->FileName, L"embedded") == 0) || + (StriCmp(DirEntry->FileName, L"random") == 0)) { + ThemePtr = NULL; + } else { + ThemeNameArray.Add(DirEntry->FileName); + } + } + } + DBG("\n"); + if (ThemePtr) { + FreePool(ThemePtr); + } + } + DirIterClose(&DirIter); } -REFIT_ABSTRACT_MENU_ENTRY* SubMenuProperties() +// +// secondary main entry point +// +EFI_STATUS +EFIAPI +RefitMainMain (IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable) { - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; + EFI_STATUS Status; + XBool MainLoopRunning = true; + XBool ReinitDesktop = true; + XBool AfterTool = false; + REFIT_ABSTRACT_MENU_ENTRY *ChosenEntry = NULL; + REFIT_ABSTRACT_MENU_ENTRY *DefaultEntry = NULL; + REFIT_ABSTRACT_MENU_ENTRY *OptionEntry = NULL; + INTN DefaultIndex; + UINTN MenuExit; + UINTN i; + EFI_TIME Now; + XBool HaveDefaultVolume; + REFIT_MENU_SCREEN BootScreen; + BootScreen.isBootScreen = true; //other screens will be constructed as false + + MemLogInit(); + + // bootstrap + gST = SystemTable; + gImageHandle = ImageHandle; + gBS = SystemTable->BootServices; + gRT = SystemTable->RuntimeServices; + /*Status = */EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid, (void **) &gDS); + + + InitBooterLog(); - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_DEVICES, "Properties->"_XS8); +// ConsoleInHandle = SystemTable->ConsoleInHandle; + +//#define DEBUG_ERALY_CRASH +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step1"); +// PauseForKey(); +#endif + +#ifdef DEBUG_ON_SERIAL_PORT + SerialPortInitialize(); +#endif - for ( size_t idx = 0 ; idx < gSettings.Devices.Properties.PropertyArray.size(); ++idx) { - SETTINGS_DATA::DevicesClass::PropertiesClass::PropertyClass& Prop = gSettings.Devices.Properties.PropertyArray[idx]; + EFI_LOADED_IMAGE* LoadedImage; + Status = gBS->HandleProtocol(gImageHandle, &gEfiLoadedImageProtocolGuid, (void **) &LoadedImage); - if ( idx > 0 ) SubScreen->AddMenuInfo_f("------------"); - SubScreen->AddMenuInfo_f("%ls", Prop.DevicePathAsString.wc_str()); - for ( size_t idxChild = 0 ; idxChild < Prop.propertiesArray.size(); ++idxChild) { - SETTINGS_DATA::DevicesClass::SimplePropertyClass& Props = Prop.propertiesArray[idxChild]; - CreateMenuProps(SubScreen, &Props); +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step2"); +// PauseForKey(); +#endif + +// if ( !EFI_ERROR(Status) ) { +// XString8 msg = S8Printf("CloverX64 : Image base = 0x%llX\n", (uintptr_t)LoadedImage->ImageBase); // do not change, it's used by grep to feed the debugger +// SerialPortWrite((UINT8*)msg.c_str(), msg.length()); +// } + if ( !EFI_ERROR(Status) ) { + DBG("CloverX64 : Image base = 0x%llX\n", (uintptr_t)LoadedImage->ImageBase); // do not change, it's used by grep to feed the debugger + DBG("Clover ImageHandle = %llx\n", (uintptr_t)ImageHandle); +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step3"); +// PauseForKey(); +#endif } +#ifdef JIEF_DEBUG + gBS->Stall(2500000); // to give time to gdb to connect +// PauseForKey(); +#endif } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - Entry->SubScreen = SubScreen; - return Entry; -} -REFIT_ABSTRACT_MENU_ENTRY* SubMenuPCI() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_USB, "PCI devices->"_XS8); - - SubScreen->AddMenuItemInput(74, "USB Ownership", false); - SubScreen->AddMenuItemInput(92, "USB Injection", false); - SubScreen->AddMenuItemInput(93, "Inject ClockID", false); - SubScreen->AddMenuItemInput(106, "Inject EFI Strings", false); - SubScreen->AddMenuItemInput(107, "No Default Properties", false); - SubScreen->AddMenuItemInput(97, "FakeID LAN:", true); - SubScreen->AddMenuItemInput(98, "FakeID WIFI:", true); - SubScreen->AddMenuItemInput(99, "FakeID SATA:", true); - SubScreen->AddMenuItemInput(100, "FakeID XHCI:", true); - SubScreen->AddMenuItemInput(103, "FakeID IMEI:", true); - SubScreen->AddMenuEntry(SubMenuProperties(), true); - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - Entry->SubScreen = SubScreen; - return Entry; -} +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step4"); +// PauseForKey(); +#endif +#ifdef CLOVER_BUILD + // BE CAREFUL. construct_globals_objects will call ctor on every static struct and classes. + // For example, if you do "gCPUStructure.TSCCalibr = GetMemLogTscTicksPerSecond();" before this point, it will be erased by construct_globals_objects() + construct_globals_objects(gImageHandle); +#endif -REFIT_ABSTRACT_MENU_ENTRY* SubMenuThemes() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_MENU_SWITCH *InputBootArgs; - UINTN i; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_THEME, "Themes->"_XS8); - - SubScreen->AddMenuInfoLine_f("Installed themes:"); - //add embedded - SubScreen->AddMenuItemSwitch(3, "embedded", false); - - for (i = 0; i < ThemeNameArray.size(); i++) { - InputBootArgs = new REFIT_MENU_SWITCH; - InputBootArgs->Title.takeValueFrom(ThemeNameArray[i]); - InputBootArgs->Row = i + 1; - InputBootArgs->Item = &InputItems[3]; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + MemoryTrackerInstallHook(); -REFIT_ABSTRACT_MENU_ENTRY* SubMenuGUI() -{ - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; + gCPUStructure.TSCCalibr = GetMemLogTscTicksPerSecond(); //ticks for 1second - // create the entry in the options menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_GUI, "GUI tuning->"_XS8); +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step5"); + PauseForKey(); +#endif - // submenu description - SubScreen->AddMenuInfoLine_f("Choose options to tune the Interface"); +#ifdef JIEF_DEBUG +// all_tests(); +// PauseForKey(L"press\n"); +#endif - SubScreen->AddMenuItemInput(70, "Pointer Speed:", true); - SubScreen->AddMenuItemInput(72, "Mirror Move", false); - SubScreen->AddMenuEntry(SubMenuThemes(), true); + gRT->GetTime(&Now, NULL); - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + Status = InitRefitLib(gImageHandle); // From here, debug.log starts to be saved because InitRefitLib call self.initialize() + if (EFI_ERROR(Status)) + return Status; +#ifdef DEBUG_ERALY_CRASH + SystemTable->ConOut->OutputString(SystemTable->ConOut, L"Step6"); + PauseForKey(); +#endif -/* - * This is a simple and user friendly submenu which makes it possible to modify - * the System Integrity Protection configuration from the Clover's GUI. - * Author: Needy. - * The below function is based on the SubMenuDsdtFix function. - */ -REFIT_ABSTRACT_MENU_ENTRY* SubMenuCSR() -{ - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - // create the entry in the main menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_CSR, NullXString8); - - // submenu description - SubScreen->AddMenuInfoLine_f("Modify the System Integrity Protection configuration."); - SubScreen->AddMenuInfoLine_f("All configuration changes apply to the entire machine."); - - // available configurations - SubScreen->AddMenuCheck("Allow Untrusted Kexts", CSR_ALLOW_UNTRUSTED_KEXTS, 66); - SubScreen->AddMenuCheck("Allow Unrestricted FS", CSR_ALLOW_UNRESTRICTED_FS, 66); - SubScreen->AddMenuCheck("Allow Task For PID", CSR_ALLOW_TASK_FOR_PID, 66); - SubScreen->AddMenuCheck("Allow Kernel Debuger", CSR_ALLOW_KERNEL_DEBUGGER, 66); - SubScreen->AddMenuCheck("Allow Apple Internal", CSR_ALLOW_APPLE_INTERNAL, 66); - SubScreen->AddMenuCheck("Allow Unrestricted DTrace", CSR_ALLOW_UNRESTRICTED_DTRACE, 66); - SubScreen->AddMenuCheck("Allow Unrestricted NVRAM", CSR_ALLOW_UNRESTRICTED_NVRAM, 66); - SubScreen->AddMenuCheck("Allow Device Configuration", CSR_ALLOW_DEVICE_CONFIGURATION, 66); - SubScreen->AddMenuCheck("Allow Any Recovery OS", CSR_ALLOW_ANY_RECOVERY_OS, 66); - SubScreen->AddMenuCheck("Allow Unapproved Kexts", CSR_ALLOW_UNAPPROVED_KEXTS, 66); - SubScreen->AddMenuCheck("Allow Executable Policy Override", CSR_ALLOW_EXECUTABLE_POLICY_OVERRIDE, 66); - SubScreen->AddMenuCheck("Allow Non-authenticated Root", CSR_ALLOW_NON_AUTHENTICATED_ROOT, 66); - - // return - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - ModifyTitles(Entry); - return Entry; -} -/* -REFIT_ABSTRACT_MENU_ENTRY* SubMenuBLC() -{ - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - // create the entry in the main menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_BLC, NullXString8); - - // submenu description - SubScreen->AddMenuInfoLine_f("Modify flags for boot.efi"); - - SubScreen->AddMenuCheck("Reboot On Panic", kBootArgsFlagRebootOnPanic, 65); - SubScreen->AddMenuCheck("Hi DPI", kBootArgsFlagHiDPI, 65); - SubScreen->AddMenuCheck("Black Screen", kBootArgsFlagBlack, 65); - SubScreen->AddMenuCheck("CSR Active Config", kBootArgsFlagCSRActiveConfig, 65); - SubScreen->AddMenuCheck("CSR Pending Config", kBootArgsFlagCSRConfigMode, 65); - SubScreen->AddMenuCheck("CSR Boot", kBootArgsFlagCSRBoot, 65); - SubScreen->AddMenuCheck("Black Background", kBootArgsFlagBlackBg, 65); - SubScreen->AddMenuCheck("Login UI", kBootArgsFlagLoginUI, 65); - SubScreen->AddMenuCheck("Install UI", kBootArgsFlagInstallUI, 65); - - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - ModifyTitles(Entry); - return Entry; -} -*/ -REFIT_ABSTRACT_MENU_ENTRY* SubMenuSystem() -{ - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; +// firmware detection + gFirmwareClover = StrCmp(gST->FirmwareVendor, L"CLOVER") == 0; + if (!gFirmwareRevision) { +// gFirmwareRevision = P__oolPrint(L"%d", gST->FirmwareRevision); + } + DataHubInstall (ImageHandle, SystemTable); + InitializeConsoleSim(); - // create the entry in the options menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_SYSTEM, "System Parameters->"_XS8); + DbgHeader("Starting Clover"); + if (Now.TimeZone < -1440 || Now.TimeZone > 1440) { + MsgLog("Now is %02d.%02d.%d, %02d:%02d:%02d (GMT)\n", + Now.Day, Now.Month, Now.Year, Now.Hour, Now.Minute, Now.Second); + } else { + MsgLog("Now is %02d.%02d.%d, %02d:%02d:%02d (GMT+%d)\n", + Now.Day, Now.Month, Now.Year, Now.Hour, Now.Minute, Now.Second, gSettings.GUI.Timezone); + } + //MsgLog("Starting Clover rev %ls on %ls EFI\n", gFirmwareRevision, gST->FirmwareVendor); + MsgLog("Starting %s on %ls EFI\n", gRevisionStr, gST->FirmwareVendor); + MsgLog("Build id: %s\n", gBuildId.c_str()); + if ( gBuildInfo ) DBG("Build with: [%s]\n", gBuildInfo); +#ifdef JIEF_DEBUG + displayFreeMemory(""_XS8); +#endif - // submenu description - SubScreen->AddMenuInfoLine_f("Choose options for booted OS"); + //dumping SETTING structure + // if you change something in Platform.h, please uncomment and test that all offsets + // are natural aligned i.e. pointers are 8 bytes aligned + /* + DBG("Settings offsets:\n"); + DBG(" OEMProduct: %X\n", OFFSET_OF(SETTINGS_DATA, OEMProduct)); + DBG(" DefaultVolume: %X\n", OFFSET_OF(SETTINGS_DATA, DefaultVolume)); + DBG(" DefaultLoader: %X\n", OFFSET_OF(SETTINGS_DATA, DefaultLoader)); + DBG(" ResetAddr: %X\n", OFFSET_OF(SETTINGS_DATA, ResetAddr)); + DBG(" FixDsdt: %X\n", OFFSET_OF(SETTINGS_DATA, FixDsdt)); + DBG(" FakeATI: %X\n", OFFSET_OF(SETTINGS_DATA, FakeATI)); + DBG(" PatchVBiosBytes:%X\n", OFFSET_OF(SETTINGS_DATA, PatchVBiosBytes)); + DBG(" VRAM: %X\n", OFFSET_OF(SETTINGS_DATA, VRAM)); + DBG(" SecureBootWhiteListCount: %X\n", OFFSET_OF(SETTINGS_DATA, SecureBootWhiteListCount)); + DBG(" LegacyBoot: %X\n", OFFSET_OF(SETTINGS_DATA, LegacyBoot)); + DBG(" HVHideStrings: %X\n", OFFSET_OF(SETTINGS_DATA, HVHideStrings)); + DBG(" PointerSpeed: %X\n", OFFSET_OF(SETTINGS_DATA, PointerSpeed)); + DBG(" RtMLB: %X\n", OFFSET_OF(SETTINGS_DATA, RtMLB)); + DBG(" ConfigName: %X\n", OFFSET_OF(SETTINGS_DATA, ConfigName)); + DBG(" PointerSpeed: %X\n", OFFSET_OF(SETTINGS_DATA, PointerSpeed)); + DBG(" PatchDsdtNum: %X\n", OFFSET_OF(SETTINGS_DATA, PatchDsdtNum)); + DBG(" LenToReplace: %X\n", OFFSET_OF(SETTINGS_DATA, LenToReplace)); + DBG(" ACPIDropTables: %X\n", OFFSET_OF(SETTINGS_DATA, ACPIDropTables)); + DBG(" CustomEntries: %X\n", OFFSET_OF(SETTINGS_DATA, CustomEntries)); + DBG(" CustomTool: %X\n", OFFSET_OF(SETTINGS_DATA, CustomTool)); + DBG(" AddProperties: %X\n", OFFSET_OF(SETTINGS_DATA, AddProperties)); + DBG(" BlockKexts: %X\n", OFFSET_OF(SETTINGS_DATA, BlockKexts)); + */ + + // disable EFI watchdog timer + gBS->SetWatchdogTimer(0x0000, 0x0000, 0x0000, NULL); +// ZeroMem((void*)&gSettings, sizeof(SETTINGS_DATA)); + + Status = InitializeUnicodeCollationProtocol(); + if (EFI_ERROR(Status)) { + DBG("UnicodeCollation Status=%s\n", efiStrError(Status)); + } + +// Status = gBS->HandleProtocol(ConsoleInHandle, &gEfiSimpleTextInputExProtocolGuid, (void **)&SimpleTextEx); +// if ( EFI_ERROR(Status) ) { +// SimpleTextEx = NULL; +// } +// DBG("SimpleTextEx Status=%s\n", efiStrError(Status)); - SubScreen->AddMenuItemInput(2, "Block kext:", true); - SubScreen->AddMenuItemInput(51, "Set OS version if not detected:", true); - SubScreen->AddMenuItemInput(118, "Booter Cfg Command:", true); - SubScreen->AddMenuItemInput(129, "Reset SMC", false); + gConf.InitialisePlatform(); - SubScreen->AddMenuEntry(SubMenuCSR(), true); -// SubScreen->AddMenuEntry(SubMenuBLC(), true); +#ifdef JIEF_DEBUG + //DumpNvram(); +#endif - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} + /* + * saving debug.log works from here + */ -REFIT_ABSTRACT_MENU_ENTRY* SubMenuConfigs() -{ - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - REFIT_MENU_SWITCH *InputBootArgs; - UINTN i; - - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_THEME, "Configs->"_XS8); - - SubScreen->AddMenuInfoLine_f("Select a config file:"); - - for (i = 0; i < ConfigsList.size(); i++) { - InputBootArgs = new REFIT_MENU_SWITCH; - InputBootArgs->Title = ConfigsList[i]; - InputBootArgs->Row = i; - InputBootArgs->Item = &InputItems[90]; - InputBootArgs->AtClick = ActionEnter; - InputBootArgs->AtRightClick = ActionDetails; - SubScreen->AddMenuEntry(InputBootArgs, true); - } - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - return Entry; -} -REFIT_ABSTRACT_MENU_ENTRY* SubMenuQuirks() -{ - // init - REFIT_MENU_ITEM_OPTIONS *Entry; - REFIT_MENU_SCREEN *SubScreen; - - // create the entry in the main menu - Entry = newREFIT_MENU_ITEM_OPTIONS(&SubScreen, ActionEnter, SCREEN_QUIRKS, NullXString8); - Entry->Title.SWPrintf("Quirks mask [0x%04x]->", gSettings.Quirks.QuirksMask); - - // submenu description - SubScreen->AddMenuInfoLine_f("Choose options to fix memory"); - - SubScreen->AddMenuCheck("AvoidRuntimeDefrag", QUIRK_DEFRAG, 101); - SubScreen->AddMenuCheck("DevirtualiseMmio", QUIRK_MMIO, 101); - SubScreen->AddMenuCheck("DisableSingleUser", QUIRK_SU, 101); - SubScreen->AddMenuCheck("DisableVariableWrite", QUIRK_VAR, 101); - SubScreen->AddMenuCheck("DiscardHibernateMap", QUIRK_HIBER, 101); - SubScreen->AddMenuCheck("EnableSafeModeSlide", QUIRK_SAFE, 101); - SubScreen->AddMenuCheck("EnableWriteUnprotector", QUIRK_UNPROT, 101); - SubScreen->AddMenuCheck("ForceExitBootServices", QUIRK_EXIT, 101); - SubScreen->AddMenuCheck("ProtectMemoryRegions", QUIRK_REGION, 101); - SubScreen->AddMenuCheck("ProtectSecureBoot", QUIRK_SECURE, 101); - SubScreen->AddMenuCheck("ProtectUefiServices", QUIRK_UEFI, 101); - SubScreen->AddMenuCheck("ProvideCustomSlide", QUIRK_CUSTOM, 101); -//decimal - SubScreen->AddMenuItemInput(122, "ProvideMaxSlide:", true); - SubScreen->AddMenuCheck("RebuildAppleMemoryMap", QUIRK_MAP, 101); - SubScreen->AddMenuItemInput(127, "ResizeAppleGpuBars:", true); - SubScreen->AddMenuCheck("SetupVirtualMap", QUIRK_VIRT, 101); - SubScreen->AddMenuCheck("SyncRuntimePermissions", QUIRK_PERM, 101); - - SubScreen->AddMenuItemInput(130, "TscSyncTimeout:", true); + { +// UINT32 machineSignature = 0; + EFI_ACPI_2_0_FIXED_ACPI_DESCRIPTION_TABLE *FadtPointer = NULL; + EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *Facs = NULL; + +// DBG("---dump hibernations data---\n"); + FadtPointer = GetFadt(); + if (FadtPointer != NULL) { + Facs = (EFI_ACPI_4_0_FIRMWARE_ACPI_CONTROL_STRUCTURE*)(UINTN)(FadtPointer->FirmwareCtrl); + /* + DBG(" Firmware wake address=%08lx\n", Facs->FirmwareWakingVector); + DBG(" Firmware wake 64 addr=%16llx\n", Facs->XFirmwareWakingVector); + DBG(" Hardware signature =%08lx\n", Facs->HardwareSignature); + DBG(" GlobalLock =%08lx\n", Facs->GlobalLock); + DBG(" Flags =%08lx\n", Facs->Flags); + */ + machineSignature = Facs->HardwareSignature; + } +#if HIBERNATE_DUMP_DATA +//------------------------------------------------------ + DumpVariable(L"Boot0082", gEfiGlobalVariableGuid, 8); + DumpVariable(L"boot-switch-vars", gEfiAppleBootGuid, -1); + DumpVariable(L"boot-signature", gEfiAppleBootGuid, -1); + DumpVariable(L"boot-image-key", gEfiAppleBootGuid, -1); + DumpVariable(L"boot-image", gEfiAppleBootGuid, 0); +//----------------------------------------------------------- + +#endif // + } + +#if 0 + //testing place + { + //#define ARRAY_SIZE(Array) (sizeof (Array) / sizeof ((Array)[0])) + #define L_STR_LEN(String) (ARRAY_SIZE (String) - 1) +DBG("strlen '<' =%ld or %lld\n", L_STR_LEN("<"), AsciiStrLen("<")); + DBG(" size CHAR8=%ld\n", sizeof(CHAR8)); + DBG(" size CHAR16=%ld\n", sizeof(CHAR16)); + DBG(" size wchar_t=%ld\n", sizeof(wchar_t)); + DBG(" size char32_t=%ld\n", sizeof(char32_t)); + DBG(" size char16_t=%ld\n", sizeof(char16_t)); + const CHAR16 aaa[] = L"12345 "; + const CHAR8 *bbb = "12345 "; + DBG(" string %ls, size=%lld, len=%lld sizeof=%ld iStrLen=%lld\n", aaa, StrSize(aaa), StrLen(aaa), sizeof(aaa), iStrLen(bbb, 10)); + const CHAR8* ccc = "Выход "; + DBG(" string %s, size=%lld, len=%lld sizeof=%ld iStrLen=%lld\n", ccc, AsciiStrSize(ccc), AsciiStrLen(ccc), sizeof(ccc), iStrLen(ccc, 10)); + XString8 ddd = "Выход "_XS8; + // size_t sizex = ddd.allocatedSize(); + DBG(" xstring %s, asize=%ld, sizeinbyte=%ld sizeof=%ld lastcharat=%ld\n", ddd.c_str(), ddd.allocatedSize(), + ddd.sizeInBytes(), sizeof(ddd), ddd.indexOf(ddd.lastChar())); + CHAR8 compatible[64]; + UINT32 FakeLAN = 0x0030168c; + UINT32 FakeID = FakeLAN >> 16; + UINT32 FakeVendor = FakeLAN & 0xFFFF; + snprintf(compatible, 64, "pci%x,%x", FakeVendor, FakeID); + DBG(" FakeLAN = 0x%x\n", FakeLAN); + DBG(" Compatible=%s strlen=%ld sizeof=%ld iStrLen=%lld\n", compatible, + strlen(compatible), sizeof(compatible), iStrLen(compatible, 64)); +// LowCase(compatible); +// DBG(" Low Compatible=%s strlen=%ld sizeof=%ld iStrLen=%lld\n", compatible, +// strlen(compatible), sizeof(compatible), iStrLen(compatible, 64)); + + DBG("void*=%ld int=%ld long=%ld longlong=%ld enum=%ld\n", + sizeof(void*), sizeof(int), sizeof(long int), sizeof(long long), sizeof(EFI_ALLOCATE_TYPE)); + /* + Results + 1:200 0:025 size CHAR8=1 + 1:226 0:025 size CHAR16=2 + 1:251 0:024 size wchar_t=2 + 1:275 0:024 size char16_t=2 + 1:381 0:000 string 12345 , size=16, len=7 sizeof=16 iStrLen=5 + 1:381 0:000 string Выход , size=13, len=12 sizeof=8 iStrLen=10 + 1:381 0:000 xstring Выход , asize=0, sizeinbyte=11 sizeof=16 lastcharat=5 + 1:381 0:000 FakeLAN = 0x30168c + 1:381 0:000 Compatible=pci168c,30 strlen=10 sizeof=64 iStrLen=10 + 1:430 0:025 void*=8 int=4 long=8 longlong=8 enum=4 + */ + } +#endif + if (!GlobalConfig.isFastBoot()) { + GetListOfThemes(); + GetListOfConfigs(); +// SmbiosList.setEmpty(); +// SmbiosList.AddReference(new XStringW(L"auto"_XSW), true); + } +// ThemeX->FillByEmbedded(); //init XTheme before EarlyUserSettings + { + void *Value = NULL; + UINTN Size = 0; + //read aptiofixflag from nvram for special boot + Status = GetVariable2(L"aptiofixflag", gEfiAppleBootGuid, &Value, &Size); + if (!EFI_ERROR(Status)) { + GlobalConfig.SpecialBootMode = true; + FreePool(Value); + DBG("Fast option enabled\n"); + } + } + +// for (i=0; i<2; i++) { +// if (gConfigDict[i]) { +// GetEarlyUserSettings(gConfigDict[i], gSettings); +// } +// } + +#ifdef ENABLE_SECURE_BOOT + // Install secure boot shim + if (EFI_ERROR(Status = InstallSecureBoot())) { + PauseForKey("Secure boot failure!\n"_XS8); + return Status; + } +#endif // ENABLE_SECURE_BOOT + + MainMenu.TimeoutSeconds = gSettings.Boot.Timeout >= 0 ? gSettings.Boot.Timeout : 0; + //DBG("LoadDrivers() start\n"); + LoadDrivers(); - SubScreen->AddMenuEntry(&MenuEntryReturn, false); - ModifyTitles(Entry); + Status = gBS->LocateProtocol(gEmuVariableControlProtocolGuid, NULL, (void**)&gEmuVariableControl); + if (EFI_ERROR(Status)) { + gEmuVariableControl = NULL; + } + if (gEmuVariableControl != NULL) { + gEmuVariableControl->InstallEmulation(gEmuVariableControl); + } + + DbgHeader("InitScreen"); + + if (!GlobalConfig.isFastBoot()) { + // init screen and dump video modes to log + if (gDriversFlags.VideoLoaded) { + InitScreen(false); + } else { + InitScreen(!gFirmwareClover); // ? false : true); + } + //DBG("DBG: setup screen\n"); + SetupScreen(); + } else { + InitScreen(false); + } + + //DBG("ReinitRefitLib\n"); + //Now we have to reinit handles + Status = ReinitRefitLib(); + if (EFI_ERROR(Status)){ + // DebugLog(2, " %s", efiStrError(Status)); + PauseForKey("Error reinit refit."_XS8); +#ifdef ENABLE_SECURE_BOOT + UninstallSecureBoot(); +#endif // ENABLE_SECURE_BOOT + return Status; + } + + ThemeX = new XTheme(); + + // DBG("DBG: messages\n"); + if (!gSettings.Boot.NoEarlyProgress && !GlobalConfig.isFastBoot() && gSettings.Boot.Timeout>0) { + XStringW Message = SWPrintf(" Welcome to Clover %ls ", gFirmwareRevision); + BootScreen.DrawTextXY(Message, (UGAWidth >> 1), UGAHeight >> 1, X_IS_CENTER); + BootScreen.DrawTextXY(L"... testing hardware ..."_XSW, (UGAWidth >> 1), (UGAHeight >> 1) + 20, X_IS_CENTER); + } + +// DumpBiosMemoryMap(); + +// PrintMemoryMap(); + + GuiEventsInitialize(); + + //DBG("ScanSPD() start\n"); + ScanSPD(); + //DBG("ScanSPD() end\n"); + + SetPrivateVarProto(); +// GetDefaultSettings(); + GetAcpiTablesList(); + + + if (!gSettings.Boot.NoEarlyProgress && !GlobalConfig.isFastBoot() && gSettings.Boot.Timeout>0) { + XStringW Message = SWPrintf("... user settings ..."); + BootScreen.EraseTextXY(); + BootScreen.DrawTextXY(Message, (UGAWidth >> 1), (UGAHeight >> 1) + 20, X_IS_CENTER); + } - return Entry; -} + afterGetUserSettings(gSettings); + gFakeCPUID = gSettings.KernelAndKextPatches.FakeCPUID; + DBG("Set FakeCPUID: 0x%X\n", gFakeCPUID); + + HaveDefaultVolume = gSettings.Boot.DefaultVolume.notEmpty(); + if (!gFirmwareClover && + !gDriversFlags.EmuVariableLoaded && + !HaveDefaultVolume && + gSettings.Boot.Timeout == 0 && !ReadAllKeyStrokes()) { +// UEFI boot: get gEfiBootDeviceGuid from NVRAM. +// if present, ScanVolumes() will skip scanning other volumes +// in the first run. +// this speeds up loading of default macOS volume. + GetEfiBootDeviceFromNvram(); + } + + if (!gSettings.Boot.NoEarlyProgress && !GlobalConfig.isFastBoot() && gSettings.Boot.Timeout>0) { + XStringW Message = SWPrintf("... scan entries ..."); + BootScreen.EraseTextXY(); + BootScreen.DrawTextXY(Message, (UGAWidth >> 1), (UGAHeight >> 1) + 20, X_IS_CENTER); + } + + AfterTool = false; + gGuiIsReady = true; + GlobalConfig.gBootChanged = true; + GlobalConfig.gThemeChanged = true; + + do { + if (GlobalConfig.gBootChanged && GlobalConfig.gThemeChanged) { // config changed + GetListOfDsdts(); //only after GetUserSettings + GetListOfACPI(); //ssdt and other tables + } + GlobalConfig.gBootChanged = false; + MainMenu.Entries.setEmpty(); + OptionMenu.Entries.setEmpty(); + InitKextList(); + ScanVolumes(); + + // as soon as we have Volumes, find latest nvram.plist and copy it to RT vars + if (!AfterTool) { + if (gFirmwareClover || gDriversFlags.EmuVariableLoaded) { + PutNvramPlistToRtVars(); + } + } + + // log Audio devices in boot-log. This is for clients like Clover.app + GetOutputs(); + for (i = 0; i < AudioList.size(); i++) { + if (AudioList[i].Name.notEmpty()) { + // Never change this log, otherwise clients will stop interpret the output. + MsgLog("Found Audio Device %ls (%s) at index %llu\n", AudioList[i].Name.wc_str(), AudioOutputNames[AudioList[i].Device], i); + } + } + + if (!GlobalConfig.isFastBoot()) { + if (gThemeNeedInit) { + UINTN Size = 0; + CHAR8* ChoosenTheme = (CHAR8*)GetNvramVariable(L"Clover.Theme", gEfiAppleBootGuid, NULL, &Size); + InitTheme(ChoosenTheme); + FreePool(ChoosenTheme); + gThemeNeedInit = false; + } else if (GlobalConfig.gThemeChanged) { + DBG("change theme\n"); + InitTheme(NULL); + AboutMenu.Entries.setEmpty(); + HelpMenu.Entries.setEmpty(); + } + DBG("theme inited\n"); + if (ThemeX->embedded) { + DBG("Chosen embedded theme\n"); + } else { + DBG("Chosen theme %ls\n", ThemeX->Theme.wc_str()); + } + //now it is a time to set RtVariables + SetVariablesFromNvram(); + + XString8Array TmpArgs = Split<XString8Array>(gSettings.Boot.BootArgs, " "); + DBG("after NVRAM boot-args=%s\n", gSettings.Boot.BootArgs.c_str()); + GlobalConfig.OptionsBits = EncodeOptions(TmpArgs); +// DBG("initial OptionsBits %X\n", GlobalConfig.OptionsBits); + FillInputs(true); + + // scan for loaders and tools, add then to the menu + if (gSettings.GUI.Scan.LegacyFirst){ + AddCustomLegacy(); + if (!gSettings.GUI.Scan.NoLegacy) { + ScanLegacy(); + } + } + } + GetSmcKeys(true); + + // Add custom entries + AddCustomEntries(); + if (gSettings.GUI.Scan.DisableEntryScan) { + DBG("Entry scan disabled\n"); + } else { + ScanLoader(); + } -void OptionsMenu(OUT REFIT_ABSTRACT_MENU_ENTRY **ChosenEntry) -{ - REFIT_ABSTRACT_MENU_ENTRY *TmpChosenEntry = NULL; - REFIT_ABSTRACT_MENU_ENTRY *NextChosenEntry = NULL; - UINTN MenuExit = 0; - UINTN SubMenuExit; - UINTN NextMenuExit; - INTN EntryIndex = 0; - INTN SubEntryIndex = -1; //value -1 means old position to remember - INTN NextEntryIndex = -1; - - XBool OldFontStyle = ThemeX->Proportional; - ThemeX->Proportional = false; //temporary disable proportional - - - // remember, if you extended this menu then change procedures - // FillInputs and ApplyInputs - gThemeOptionsChanged = false; - - if (OptionMenu.Entries.size() == 0) { - OptionMenu.Daylight = ThemeX->Daylight; - if (!(ThemeX->HideUIFlags & HIDEUI_FLAG_MENU_TITLE_IMAGE)) { - OptionMenu.TitleImage = ThemeX->GetIcon(BUILTIN_ICON_FUNC_OPTIONS); - } - gThemeOptionsChanged = true; - OptionMenu.ID = SCREEN_OPTIONS; - OptionMenu.GetAnime(); //false; - - OptionMenu.AddMenuItemInput(0, "Boot Args:", true); - OptionMenu.AddMenuEntry( SubMenuConfigs(), true); - - if (AllowGraphicsMode) { - OptionMenu.AddMenuEntry( SubMenuGUI(), true); - } - OptionMenu.AddMenuEntry( SubMenuACPI(), true); - OptionMenu.AddMenuEntry( SubMenuChooseSmbios(), true); - // OptionMenu.AddMenuEntry( SubMenuSmbios(), true); - OptionMenu.AddMenuEntry( SubMenuBinaries(), true); - OptionMenu.AddMenuEntry( SubMenuQuirks(), true); - OptionMenu.AddMenuEntry( SubMenuGraphics(), true); - OptionMenu.AddMenuEntry( SubMenuPCI(), true); - OptionMenu.AddMenuEntry( SubMenuSpeedStep(), true); - OptionMenu.AddMenuEntry( SubMenuAudio(), true); - OptionMenu.AddMenuEntry( SubMenuAudioPort(), true); - OptionMenu.AddMenuEntry( SubMenuSystem(), true); - OptionMenu.AddMenuEntry( &MenuEntryReturn, false); - //DBG("option menu created entries=%d\n", OptionMenu.Entries.size()); - } - - while (!MenuExit) { - MenuExit = OptionMenu.RunGenericMenu(&EntryIndex, ChosenEntry); - if (MenuExit == MENU_EXIT_ESCAPE || (*ChosenEntry)->getREFIT_MENU_ITEM_RETURN()) + if (!GlobalConfig.isFastBoot()) { + if (!gSettings.GUI.Scan.LegacyFirst) { + AddCustomLegacy(); + if (!gSettings.GUI.Scan.NoLegacy) { + ScanLegacy(); + } + } + + // fixed other menu entries + if (!(ThemeX->HideUIFlags & HIDEUI_FLAG_TOOLS)) { + AddCustomTool(); + if (!gSettings.GUI.Scan.DisableToolScan) { + ScanTool(); +#ifdef ENABLE_SECURE_BOOT + // Check for secure boot setup mode + AddSecureBootTool(); +#endif // ENABLE_SECURE_BOOT + } + } + + MenuEntryOptions.Image = ThemeX->GetIcon(BUILTIN_ICON_FUNC_OPTIONS); +// DBG("Options: IconID=%lld name=%s empty=%s\n", MenuEntryOptions.Image.Id, MenuEntryOptions.Image.Name.c_str(), + if (gSettings.Boot.DisableCloverHotkeys) + MenuEntryOptions.ShortcutLetter = 0x00; + MainMenu.AddMenuEntry(&MenuEntryOptions, false); + + MenuEntryAbout.Image = ThemeX->GetIcon((INTN)BUILTIN_ICON_FUNC_ABOUT); +// DBG("About: IconID=%lld name=%s empty=%s\n", MenuEntryAbout.Image.Id, MenuEntryAbout.Image.Name.c_str(), + + if (gSettings.Boot.DisableCloverHotkeys) + MenuEntryAbout.ShortcutLetter = 0x00; + MainMenu.AddMenuEntry(&MenuEntryAbout, false); + + if (!(ThemeX->HideUIFlags & HIDEUI_FLAG_FUNCS) || MainMenu.Entries.size() == 0) { + if (gSettings.Boot.DisableCloverHotkeys) + MenuEntryReset.ShortcutLetter = 0x00; + MenuEntryReset.Image = ThemeX->GetIcon(BUILTIN_ICON_FUNC_RESET); + MainMenu.AddMenuEntry(&MenuEntryReset, false); + if (gSettings.Boot.DisableCloverHotkeys) + MenuEntryShutdown.ShortcutLetter = 0x00; + MenuEntryShutdown.Image = ThemeX->GetIcon(BUILTIN_ICON_FUNC_EXIT); + MainMenu.AddMenuEntry(&MenuEntryShutdown, false); + } + + } + // wait for user ACK when there were errors + FinishTextScreen(false); +#if CHECK_SMC + DumpSmcKeys(); +#endif + + DefaultIndex = FindDefaultEntry(); +// DBG("DefaultIndex=%lld and MainMenu.Entries.size()=%llu\n", DefaultIndex, MainMenu.Entries.size()); + if ((DefaultIndex >= 0) && (DefaultIndex < (INTN)MainMenu.Entries.size())) { + DefaultEntry = &MainMenu.Entries[DefaultIndex]; + } else { + DefaultEntry = NULL; + } + + MainLoopRunning = true; + if (DefaultEntry && (GlobalConfig.isFastBoot() || + (gSettings.Boot.SkipHibernateTimeout && + DefaultEntry->getLOADER_ENTRY() + && OSFLAG_ISSET(DefaultEntry->getLOADER_ENTRY()->Flags, OSFLAG_HIBERNATED)))) { + if (DefaultEntry->getLOADER_ENTRY()) { + DefaultEntry->StartLoader(); + } else if (DefaultEntry->getLEGACY_ENTRY()){ + DefaultEntry->StartLegacy(); + } + gSettings.Boot.FastBoot = false; //Hmm... will never be here + } +#ifdef JIEF_DEBUG +//MainMenu.TimeoutSeconds=1; +//DefaultEntry = NULL; +//DefaultIndex = MainMenu.Entries.length()-1; // this should be "Exit Clover" +#endif + AfterTool = false; + gEvent = 0; //clear to cancel loop + while (MainLoopRunning) { + if (gSettings.Boot.Timeout == 0 && DefaultEntry != NULL && !ReadAllKeyStrokes()) { + // go strait to DefaultVolume loading + MenuExit = MENU_EXIT_TIMEOUT; + } else { + MainMenu.GetAnime(); + if (GlobalConfig.gThemeChanged) { + GlobalConfig.gThemeChanged = false; + ThemeX->ClearScreen(); + } +#ifdef JIEF_DEBUG +displayFreeMemory("Before RunMainMenu"_XS8); +#endif + MenuExit = MainMenu.RunMainMenu(DefaultIndex, &ChosenEntry); + } +// DBG("exit from MainMenu %llu ChosenEntry=%zu\n", MenuExit, MainMenu.Entries.indexOf(*ChosenEntry)); //MENU_EXIT_ENTER=(1) MENU_EXIT_DETAILS=3 + // disable default boot - have sense only in the first run + gSettings.Boot.Timeout = -1; + if ((DefaultEntry != NULL) && (MenuExit == MENU_EXIT_TIMEOUT)) { + if (DefaultEntry->getLOADER_ENTRY()) { + DefaultEntry->StartLoader(); + } else if (DefaultEntry->getLEGACY_ENTRY()){ + DefaultEntry->StartLegacy(); + } + // if something goes wrong - break main loop to reinit volumes + break; + } + + if (MenuExit == MENU_EXIT_OPTIONS){ + GlobalConfig.gBootChanged = false; + OptionsMenu(&OptionEntry); + if (GlobalConfig.gBootChanged) { + AfterTool = true; + MainLoopRunning = false; + break; + } + continue; + } + + if (MenuExit == MENU_EXIT_HELP){ + HelpRefit(); + continue; + } + + // EjectVolume + if (MenuExit == MENU_EXIT_EJECT){ + Status = EFI_SUCCESS; + if (ChosenEntry->getLOADER_ENTRY() ) { + Status = EjectVolume(ChosenEntry->getLOADER_ENTRY()->Volume); + } + if ( ChosenEntry->getLEGACY_ENTRY() ) { + Status = EjectVolume(ChosenEntry->getLEGACY_ENTRY()->Volume); + } + if (!EFI_ERROR(Status)) { + break; //main loop is broken so Reinit all + } + continue; + } + + // Hide toggle + if (MenuExit == MENU_EXIT_HIDE_TOGGLE) { + MainMenu.Entries.includeHidden = !MainMenu.Entries.includeHidden; + continue; + } + + // We don't allow exiting the main menu with the Escape key. + if (MenuExit == MENU_EXIT_ESCAPE){ + break; //refresh main menu + // continue; + } + + if ( ChosenEntry->getREFIT_MENU_ITEM_RESET() ) { // Restart + if (MenuExit == MENU_EXIT_DETAILS) { + + //do clear cmos as for AMI BIOS + // not sure for more robust method + IoWrite8 (PCAT_RTC_ADDRESS_REGISTER, 0x10); + IoWrite8 (PCAT_RTC_DATA_REGISTER, 0x0); + IoWrite8 (PCAT_RTC_ADDRESS_REGISTER, 0x11); + IoWrite8 (PCAT_RTC_DATA_REGISTER, 0x0); +// or may be +// IoWrite8 (PCAT_RTC_ADDRESS_REGISTER, 0x17); +// IoWrite8 (PCAT_RTC_DATA_REGISTER, 0x17); + +// } + } + // Attempt warm reboot + gRT->ResetSystem(EfiResetWarm, EFI_SUCCESS, 0, NULL); + // Warm reboot may not be supported attempt cold reboot + gRT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); + // Terminate the screen and just exit + TerminateScreen(); + MainLoopRunning = false; + ReinitDesktop = false; + AfterTool = true; + } + + if ( ChosenEntry->getREFIT_MENU_ITEM_SHUTDOWN() ) { // It is not Shut Down, it is Exit from Clover + TerminateScreen(); + // gRT->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); + MainLoopRunning = false; // just in case we get this far + ReinitDesktop = false; + AfterTool = true; + } + if ( ChosenEntry->getREFIT_MENU_ITEM_OPTIONS() ) { // Options like KernelFlags, DSDTname etc. + GlobalConfig.gBootChanged = false; + OptionsMenu(&OptionEntry); + if (GlobalConfig.gBootChanged) + AfterTool = true; + if (GlobalConfig.gBootChanged || GlobalConfig.gThemeChanged) // If theme has changed reinit the desktop + MainLoopRunning = false; + } + if ( ChosenEntry->getREFIT_MENU_ITEM_ABOUT() ) { // About rEFIt + AboutRefit(); + } + + /* -- not passed here +// case TAG_HELP: + HelpRefit(); break; - if (MenuExit == MENU_EXIT_ENTER || MenuExit == MENU_EXIT_DETAILS) { - //enter input dialog or subscreen - if ((*ChosenEntry)->SubScreen != NULL) { - SubMenuExit = 0; - while (!SubMenuExit) { - SubMenuExit = (*ChosenEntry)->SubScreen->RunGenericMenu(&SubEntryIndex, &TmpChosenEntry); - if (SubMenuExit == MENU_EXIT_ESCAPE || TmpChosenEntry->getREFIT_MENU_ITEM_RETURN() ){ - ApplyInputs(); - ModifyTitles(*ChosenEntry); - break; + */ + if ( ChosenEntry->getLOADER_ENTRY() ) { // Boot OS via .EFI loader + SetBootCurrent(ChosenEntry->getLOADER_ENTRY()); + ChosenEntry->StartLoader(); + //if boot.efi failed we should somehow exit from the loop + TerminateScreen(); + MainLoopRunning = false; + ReinitDesktop = false; + AfterTool = true; + } + if ( ChosenEntry->getLEGACY_ENTRY() ) { // Boot legacy OS + if (StrCmp(gST->FirmwareVendor, L"Phoenix Technologies Ltd.") == 0 && + gST->Hdr.Revision >> 16 == 2 && (gST->Hdr.Revision & ((1 << 16) - 1)) == 0){ + // Phoenix SecureCore Tiano 2.0 can't properly initiate LegacyBios protocol when called externally + // which results in "Operating System not found" message coming from BIOS + // in this case just quit Clover to enter BIOS again + TerminateScreen(); + MainLoopRunning = false; + ReinitDesktop = false; + AfterTool = true; + } else { + SetBootCurrent(ChosenEntry->getLEGACY_ENTRY()); + ChosenEntry->StartLegacy(); + } + } + if ( ChosenEntry->getREFIT_MENU_ENTRY_LOADER_TOOL() ) { // Start a EFI tool + ChosenEntry->StartTool(); + TerminateScreen(); //does not happen + // return EFI_SUCCESS; + // BdsLibConnectAllDriversToAllControllers(); + // PauseForKey(L"Returned from StartTool\n"); + MainLoopRunning = false; + AfterTool = true; + } + #ifdef ENABLE_SECURE_BOOT +//log_technical_bug("not done yet"); +// if ( ChosenEntry->getREFIT_MENU_ENTRY_SECURE_BOOT() ) { // Try to enable secure boot +// EnableSecureBoot(); +// MainLoopRunning = false; +// AfterTool = true; +// } +// +// if ( ChosenEntry->getREFIT_MENU_ENTRY_SECURE_BOOT_CONFIG() ) { // Configure secure boot +// MainLoopRunning = !ConfigureSecureBoot(); +// AfterTool = true; +// } + #endif // ENABLE_SECURE_BOOT +// DBG("come to Clover entry with letter %c\n", ChosenEntry->ShortcutLetter); + REFIT_MENU_ENTRY_CLOVER* LoaderEntry = ChosenEntry->getREFIT_MENU_ENTRY_CLOVER(); + if ((ChosenEntry->ShortcutLetter == L'C') || LoaderEntry != NULL ) { // Clover options +// DBG("enter Clover entry\n"); + + if (LoaderEntry->LoadOptions.notEmpty()) { + + // we are uninstalling in case user selected Clover Options and EmuVar is installed + // because adding bios boot option requires access to real nvram + //Slice: sure? + /* if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); } - if (SubMenuExit == MENU_EXIT_ENTER || MenuExit == MENU_EXIT_DETAILS) { - if (TmpChosenEntry->SubScreen != NULL) { - NextMenuExit = 0; - while (!NextMenuExit) { - NextMenuExit = TmpChosenEntry->SubScreen->RunGenericMenu(&NextEntryIndex, &NextChosenEntry); - if (NextMenuExit == MENU_EXIT_ESCAPE || NextChosenEntry->getREFIT_MENU_ITEM_RETURN() ){ - ApplyInputs(); - ModifyTitles(TmpChosenEntry); - break; - } - if (NextMenuExit == MENU_EXIT_ENTER || MenuExit == MENU_EXIT_DETAILS) { - // enter input dialog - NextMenuExit = 0; - ApplyInputs(); - ModifyTitles(TmpChosenEntry); - } - } //while(!NextMenuExit) - } - // enter input dialog - SubMenuExit = 0; - ApplyInputs(); - ModifyTitles(TmpChosenEntry); + */ + // DBG(" Clover entry not empty\n"); + if ( LoaderEntry->LoadOptions.contains(L"BO-ADD") ) { + // DBG(" BO-ADD"); + XStringW Description; + CONST CHAR16 *LoaderName; + INTN EntryIndex, NameSize, Name2Size; + LOADER_ENTRY *Entry; + UINT8 *OptionalData; + UINTN OptionalDataSize; + UINTN BootNum; + // EFI_HANDLE UsedHandle = 0; + + PrintBootOptions(false); + + for (EntryIndex = 0; EntryIndex < (INTN)MainMenu.Entries.size(); EntryIndex++) { + if (MainMenu.Entries[EntryIndex].Row != 0) { + continue; + } + if (!MainMenu.Entries[EntryIndex].getLOADER_ENTRY()) { + continue; + } + + Entry = (LOADER_ENTRY *)MainMenu.Entries[EntryIndex].getLOADER_ENTRY(); + XStringW& VolName = Entry->Volume->VolName; + DBG("add entry for volume %ls\n", VolName.wc_str()); + if (VolName.isEmpty()) { + VolName = NullXStringW; + } + NameSize = VolName.sizeInBytes(); + Name2Size = 0; + if (Entry->LoaderPath.notEmpty()) { + LoaderName = Basename(Entry->LoaderPath.wc_str()); + } else { + LoaderName = NULL; //legacy boot + } + if (LoaderName != NULL) { + Name2Size = StrSize(LoaderName); + } + + Description = SWPrintf("Clover UEFI"); + OptionalDataSize = NameSize + Name2Size + 4 + 2; //signature + VolNameSize + OptionalData = (__typeof__(OptionalData))AllocateZeroPool(OptionalDataSize); + if (OptionalData == NULL) { + break; + } + CopyMem(OptionalData, "Clvr", 4); //signature = 0x72766c43 + CopyMem(OptionalData + 4, &NameSize, 2); + CopyMem(OptionalData + 6, VolName.wc_str(), VolName.sizeInBytes()); + if (Name2Size != 0) { + CopyMem(OptionalData + 6 + NameSize, LoaderName, Name2Size); + } +// UsedHandle = LoaderEntry->Volume->DeviceHandle; + Status = AddBootOptionForFile ( + LoaderEntry->Volume->DeviceHandle, + LoaderEntry->LoaderPath, + true, + Description.wc_str(), + OptionalData, + OptionalDataSize, + EntryIndex, + (UINT16*)&BootNum + ); + if (!EFI_ERROR(Status)) { + DBG("Entry %lld assigned option %04llX\n", EntryIndex, BootNum); + Entry->BootNum = BootNum; + } + FreePool(OptionalData); + break; + } //for (EntryIndex + + + PrintBootOptions(false); + } else if ( LoaderEntry->LoadOptions.contains(L"BO-REMOVE") ) { + PrintBootOptions(false); + Status = DeleteBootOptionForFile (LoaderEntry->Volume->DeviceHandle, + LoaderEntry->LoaderPath + ); + PrintBootOptions(false); + } else if ( LoaderEntry->LoadOptions.contains(L"BO-PRINT") ) { + PrintBootOptions(true); } - } //while(!SubMenuExit) + + } + MainLoopRunning = false; + AfterTool = true; + } + } //MainLoopRunning + UninitRefitLib(); + if (!AfterTool) { + // PauseForKey(L"After uninit"); + //reconnectAll + if (!gFirmwareClover) { + BdsLibConnectAllEfi(); + } + else { + DBG("ConnectAll after refresh menu\n"); + BdsLibConnectAllDriversToAllControllers(); } - MenuExit = 0; - } // if MENU_EXIT_ENTER + // ReinitRefitLib(); + // PauseForKey(L"After ReinitRefitLib"); + } + if (ReinitDesktop) { + DBG("ReinitRefitLib after theme change\n"); + ReinitRefitLib(); + } + // PauseForKey(L"After ReinitRefitLib"); + } while (ReinitDesktop); + + // If we end up here, things have gone wrong. Try to reboot, and if that + // fails, go into an endless loop. + //Slice - NO!!! Return to EFI GUI + // gRT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); + // EndlessIdleLoop(); + +#ifdef ENABLE_SECURE_BOOT + UninstallSecureBoot(); +#endif // ENABLE_SECURE_BOOT + + // Unload EmuVariable before returning to EFI GUI, as it should not be present when booting other Operating Systems. + // This seems critical in some UEFI implementations, such as Phoenix UEFI 2.0 + if (gEmuVariableControl != NULL) { + gEmuVariableControl->UninstallEmulation(gEmuVariableControl); } -//exit: - ThemeX->Proportional = OldFontStyle; - ApplyInputs(); + UninitializeConsoleSim (); + + delete ThemeX; // do this before destruct_globals_objects() + FreePool(BlankLine); // Convert BlankLine to XStringW instead. + TagStruct::EmptyCache(); + +#ifdef CLOVER_BUILD + destruct_globals_objects(NULL); +#endif + + return EFI_SUCCESS; +} + +// +// main entry point +// +EFI_STATUS +EFIAPI +RefitMain (IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable) +{ + MemoryTrackerInit(); + //MemoryTrackerInstallHook(); can't install hook before construct_globals_objects()... yet + + EFI_STATUS Status = RefitMainMain(ImageHandle, SystemTable); + + DBG("MT_alloc_count=%lld\n", MT_getAllocCount()); + MT_outputDanglingPtr(); + +#ifdef TagStruct_COUNT_CACHEHIT + DBG("cache hits = %zu\n", TagStruct::cachehit); + DBG("cache miss = %zu\n", TagStruct::cachemiss); +#endif + + return Status; } + diff --git a/rEFIt_UEFI/refit/menu.cpp b/rEFIt_UEFI/refit/menu.cpp index d04b84cf2..5f26aa81e 100644 --- a/rEFIt_UEFI/refit/menu.cpp +++ b/rEFIt_UEFI/refit/menu.cpp @@ -1141,6 +1141,9 @@ void AboutRefit(void) AboutMenu.AddMenuInfo_f(" stinga11, TheRacerMaster, solstice, SoThOr, DF"); AboutMenu.AddMenuInfo_f(" cecekpawon, Micky1979, Needy, joevt, ErmaC, vit9696"); AboutMenu.AddMenuInfo_f(" ath, savvas, syscl, goodwin_c, clovy, jief_machak"); + AboutMenu.AddMenuInfo_f(" chris1111, vector_sigma, LAbyOne, Florin9doi"); + AboutMenu.AddMenuInfo_f("Package credits:"); + AboutMenu.AddMenuInfo_f(" Chameleon team, crazybirdy, JrCs, chris1111"); AboutMenu.AddMenuInfo_f("Credits also:"); AboutMenu.AddMenuInfo_f(" projectosx.com, applelife.ru, insanelymac.com"); AboutMenu.AddMenuInfo_f(" ");