OpenCoreKernel.c 15.1 KB
Newer Older
V
vit9696 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/** @file
  OpenCore driver.

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

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

**/

#include <OpenCore.h>

#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/OcAppleKernelLib.h>
21
#include <Library/OcMiscLib.h>
V
vit9696 已提交
22
#include <Library/OcStringLib.h>
V
vit9696 已提交
23 24 25 26 27 28 29
#include <Library/OcVirtualFsLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiBootServicesTableLib.h>

STATIC OC_STORAGE_CONTEXT  *mOcStorage;
STATIC OC_GLOBAL_CONFIG    *mOcConfiguration;

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
STATIC
VOID
OcKernelReadDarwinVersion (
  IN  CONST UINT8   *Kernel,
  IN  UINT32        KernelSize,
  OUT CHAR8         *DarwinVersion,
  OUT UINT32        DarwinVersionSize
  )
{
  INT32   Offset;
  UINT32  Index;

  ASSERT (DarwinVersion > 0);

  Offset = FindPattern (
    (CONST UINT8 *) "Darwin Kernel Version ",
    NULL,
    L_STR_LEN ("Darwin Kernel Version "),
    Kernel,
    KernelSize,
    0
    );

  if (Offset < 0) {
    DEBUG ((DEBUG_WARN, "OC: Failed to determine kernel version\n"));
    DarwinVersion[0] = '\0';
    return;
  }

59 60
  Offset += L_STR_LEN ("Darwin Kernel Version ");

61
  for (Index = 0; Index < DarwinVersionSize - 1; ++Index, ++Offset) {
62
    if ((UINT32) Offset >= KernelSize || Kernel[Offset] == ':') {
63 64 65 66 67 68 69 70 71
      break;
    }
    DarwinVersion[Index] = (CHAR8) Kernel[Offset];
  }
  DarwinVersion[Index] = '\0';

  DEBUG ((DEBUG_INFO, "OC: Read kernel version %a\n", DarwinVersion));
}

V
vit9696 已提交
72 73 74 75 76 77 78
STATIC
UINT32
OcKernelLoadKextsAndReserve (
  IN OC_STORAGE_CONTEXT  *Storage,
  IN OC_GLOBAL_CONFIG    *Config
  )
{
V
vit9696 已提交
79 80 81 82 83 84 85
  UINT32               Index;
  UINT32               ReserveSize;
  CHAR8                *BundleName;
  CHAR8                *PlistPath;
  CHAR8                *ExecutablePath;
  CHAR16               FullPath[128];
  OC_KERNEL_ADD_ENTRY  *Kext;
V
vit9696 已提交
86 87 88 89

  ReserveSize = PRELINK_INFO_RESERVE_SIZE;

  for (Index = 0; Index < Config->Kernel.Add.Count; ++Index) {
V
vit9696 已提交
90 91
    Kext = Config->Kernel.Add.Values[Index];

V
vit9696 已提交
92
    if (!Kext->Enabled) {
V
vit9696 已提交
93 94 95
      continue;
    }

V
vit9696 已提交
96 97 98
    if (Kext->PlistDataSize == 0) {
      BundleName     = OC_BLOB_GET (&Kext->BundleName);
      PlistPath      = OC_BLOB_GET (&Kext->PlistPath);
V
vit9696 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111
      if (BundleName[0] == '\0' || PlistPath[0] == '\0') {
        DEBUG ((DEBUG_ERROR, "OC: Your config has improper for kext info\n"));
        continue;
      }

      UnicodeSPrint (
        FullPath,
        sizeof (FullPath),
        OPEN_CORE_KEXT_PATH "%a\\%a",
        BundleName,
        PlistPath
        );

V
vit9696 已提交
112 113 114
      UnicodeUefiSlashes (FullPath);

      Kext->PlistData = OcStorageReadFileUnicode (
V
vit9696 已提交
115 116
        Storage,
        FullPath,
V
vit9696 已提交
117
        &Kext->PlistDataSize
V
vit9696 已提交
118 119
        );

V
vit9696 已提交
120
      if (Kext->PlistData == NULL) {
V
vit9696 已提交
121 122 123 124
        DEBUG ((DEBUG_ERROR, "OC: Plist %s is missing for kext %s\n", FullPath, BundleName));
        continue;
      }

V
vit9696 已提交
125
      ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
126 127 128 129 130 131 132 133 134
      if (ExecutablePath[0] != '\0') {
        UnicodeSPrint (
          FullPath,
          sizeof (FullPath),
          OPEN_CORE_KEXT_PATH "%a\\%a",
          BundleName,
          ExecutablePath
          );

V
vit9696 已提交
135 136 137
        UnicodeUefiSlashes (FullPath);

        Kext->ImageData = OcStorageReadFileUnicode (
V
vit9696 已提交
138 139
          Storage,
          FullPath,
V
vit9696 已提交
140
          &Kext->ImageDataSize
V
vit9696 已提交
141 142
          );

V
vit9696 已提交
143
        if (Kext->ImageData == NULL) {
V
vit9696 已提交
144 145 146 147 148 149 150 151 152 153
          DEBUG ((DEBUG_ERROR, "OC: Image %s is missing for kext %s\n", FullPath, BundleName));
          //
          // Still continue loading?
          //
        }
      }
    }

    PrelinkedReserveKextSize (
      &ReserveSize,
V
vit9696 已提交
154 155 156
      Kext->PlistDataSize,
      Kext->ImageData,
      Kext->ImageDataSize
V
vit9696 已提交
157 158 159 160 161 162 163 164
      );
  }

  DEBUG ((DEBUG_INFO, "Kext reservation size %u\n", ReserveSize));

  return ReserveSize;
}

V
vit9696 已提交
165 166 167 168
STATIC
VOID
OcKernelApplyPatches (
  IN     OC_GLOBAL_CONFIG  *Config,
169
  IN     CONST CHAR8       *DarwinVersion,
V
vit9696 已提交
170 171 172 173 174 175 176 177 178 179 180
  IN     PRELINKED_CONTEXT *Context,
  IN OUT UINT8             *Kernel,
  IN     UINT32            Size
  )
{
  EFI_STATUS             Status;
  PATCHER_CONTEXT        Patcher;
  UINT32                 Index;
  PATCHER_GENERIC_PATCH  Patch;
  OC_KERNEL_PATCH_ENTRY  *UserPatch;
  CONST CHAR8            *Target;
181
  CONST CHAR8            *MatchKernel;
V
vit9696 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  BOOLEAN                IsKernelPatch;

  IsKernelPatch = Context == NULL;

  if (IsKernelPatch) {
    ASSERT (Kernel != NULL);

    Status = PatcherInitContextFromBuffer (
      &Patcher,
      Kernel,
      Size
      );

    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_ERROR, "OC: Kernel patcher kernel init failure - %r\n", Status));
      return;
    }
  }

201
  for (Index = 0; Index < Config->Kernel.Patch.Count; ++Index) {
V
vit9696 已提交
202 203 204
    UserPatch = Config->Kernel.Patch.Values[Index];
    Target    = OC_BLOB_GET (&UserPatch->Identifier);

V
vit9696 已提交
205
    if (!UserPatch->Enabled
V
vit9696 已提交
206 207 208 209
    || (AsciiStrCmp (Target, "kernel") == 0) != IsKernelPatch) {
      continue;
    }

210 211
    MatchKernel = OC_BLOB_GET (&UserPatch->MatchKernel);

212
    if (AsciiStrnCmp (DarwinVersion, MatchKernel, AsciiStrLen (MatchKernel)) != 0) {
213 214 215 216 217 218 219 220 221 222 223
      DEBUG ((
        DEBUG_INFO,
        "OC: Kernel patcher skips %a patch at %u due to version %a vs %a",
        Target,
        Index,
        MatchKernel,
        DarwinVersion
        ));
      continue;
    }

V
vit9696 已提交
224 225 226 227 228 229 230 231 232
    if (!IsKernelPatch) {
      Status = PatcherInitContextFromPrelinked (
        &Patcher,
        Context,
        Target
        );

      if (EFI_ERROR (Status)) {
        DEBUG ((DEBUG_ERROR, "OC: Kernel patcher %a init failure - %r\n", Target, Status));
233
        continue;
V
vit9696 已提交
234 235 236 237 238 239 240 241 242 243 244
      }
    }

    //
    // Ignore patch if:
    // - There is nothing to replace.
    // - We have neither symbolic base, nor find data.
    // - Find and replace mismatch in size.
    // - Mask and ReplaceMask mismatch in size when are available.
    //
    if (UserPatch->Replace.Size == 0
245
      || (OC_BLOB_GET (&UserPatch->Base)[0] == '\0' && UserPatch->Find.Size != UserPatch->Replace.Size)
V
vit9696 已提交
246 247 248 249 250 251 252 253
      || (UserPatch->Mask.Size > 0 && UserPatch->Find.Size != UserPatch->Mask.Size)
      || (UserPatch->ReplaceMask.Size > 0 && UserPatch->Find.Size != UserPatch->ReplaceMask.Size)) {
      DEBUG ((DEBUG_ERROR, "OC: Kernel patch %u for %a is borked\n", Index, Target));
      continue;
    }

    ZeroMem (&Patch, sizeof (Patch));

254
    if (OC_BLOB_GET (&UserPatch->Base)[0] != '\0') {
V
vit9696 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      Patch.Base  = OC_BLOB_GET (&UserPatch->Base);
    }

    if (UserPatch->Find.Size > 0) {
      Patch.Find  = OC_BLOB_GET (&UserPatch->Find);
    }

    Patch.Replace = OC_BLOB_GET (&UserPatch->Replace);

    if (UserPatch->Mask.Size > 0) {
      Patch.Mask  = OC_BLOB_GET (&UserPatch->Mask);
    }

    if (UserPatch->ReplaceMask.Size > 0) {
      Patch.ReplaceMask = OC_BLOB_GET (&UserPatch->ReplaceMask);
    }

    Patch.Size    = UserPatch->Replace.Size;
    Patch.Count   = UserPatch->Count;
    Patch.Skip    = UserPatch->Skip;
    Patch.Limit   = UserPatch->Limit;

    Status = PatcherApplyGenericPatch (&Patcher, &Patch);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_WARN, "OC: Kernel patcher failed %u for %a - %r\n", Index, Target, Status));
    }
  }
282 283 284

  if (!IsKernelPatch) {
    if (Config->Kernel.Quirks.AppleCpuPmCfgLock) {
285
      PatchAppleCpuPmCfgLock (Context);
286 287 288 289 290 291 292 293 294 295 296 297 298
    }

    if (Config->Kernel.Quirks.ExternalDiskIcons) {
      PatchForceInternalDiskIcons (Context);
    }

    if (Config->Kernel.Quirks.ThirdPartyTrim) {
      PatchThirdPartySsdTrim (Context);
    }

    if (Config->Kernel.Quirks.XhciPortLimit) {
      PatchUsbXhciPortLimit (Context);
    }
299 300 301 302
  } else {
    if (Config->Kernel.Quirks.AppleXcpmCfgLock) {
      PatchAppleXcpmCfgLock (&Patcher);
    }
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  }
}

STATIC
VOID
OcKernelBlockKexts (
  IN     OC_GLOBAL_CONFIG  *Config,
  IN     CONST CHAR8       *DarwinVersion,
  IN     PRELINKED_CONTEXT *Context
  )
{
  EFI_STATUS             Status;
  PATCHER_CONTEXT        Patcher;
  UINT32                 Index;
  OC_KERNEL_BLOCK_ENTRY  *Kext;
  CONST CHAR8            *Target;
  CONST CHAR8            *MatchKernel;

  for (Index = 0; Index < Config->Kernel.Block.Count; ++Index) {
    Kext   = Config->Kernel.Block.Values[Index];
    Target = OC_BLOB_GET (&Kext->Identifier);

V
vit9696 已提交
325
    if (!Kext->Enabled) {
326 327 328 329 330
      continue;
    }

    MatchKernel = OC_BLOB_GET (&Kext->MatchKernel);

331
    if (AsciiStrnCmp (DarwinVersion, MatchKernel, AsciiStrLen (MatchKernel)) != 0) {
332 333
      DEBUG ((
        DEBUG_INFO,
334
        "OC: Prelink blocker skips %a block at %u due to version %a vs %a",
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        Target,
        Index,
        MatchKernel,
        DarwinVersion
        ));
      continue;
    }

    Status = PatcherInitContextFromPrelinked (
      &Patcher,
      Context,
      Target
      );

    if (EFI_ERROR (Status)) {
350
      DEBUG ((DEBUG_WARN, "OC: Prelink blocker %a init failure - %r\n", Target, Status));
351 352 353 354
      continue;
    }

    Status = PatcherBlockKext (&Patcher);
355 356 357 358 359 360 361

    DEBUG ((
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
      "OC: Prelink blocker %a - %r\n",
      Target,
      Status
      ));
362
  }
V
vit9696 已提交
363 364
}

V
vit9696 已提交
365 366 367 368
STATIC
EFI_STATUS
OcKernelProcessPrelinked (
  IN     OC_GLOBAL_CONFIG  *Config,
369
  IN     CONST CHAR8       *DarwinVersion,
V
vit9696 已提交
370 371 372 373 374
  IN OUT UINT8             *Kernel,
  IN     UINT32            *KernelSize,
  IN     UINT32            AllocatedSize
  )
{
375 376 377 378 379 380 381 382
  EFI_STATUS           Status;
  PRELINKED_CONTEXT    Context;
  CHAR8                *BundleName;
  CHAR8                *ExecutablePath;
  UINT32               Index;
  CHAR8                FullPath[128];
  OC_KERNEL_ADD_ENTRY  *Kext;
  CONST CHAR8          *MatchKernel;
V
vit9696 已提交
383 384 385 386

  Status = PrelinkedContextInit (&Context, Kernel, *KernelSize, AllocatedSize);

  if (!EFI_ERROR (Status)) {
387 388 389
    OcKernelApplyPatches (Config, DarwinVersion, &Context, NULL, 0);

    OcKernelBlockKexts (Config, DarwinVersion, &Context);
V
vit9696 已提交
390 391 392 393 394

    Status = PrelinkedInjectPrepare (&Context);
    if (!EFI_ERROR (Status)) {

      for (Index = 0; Index < Config->Kernel.Add.Count; ++Index) {
395 396
        Kext = Config->Kernel.Add.Values[Index];

V
vit9696 已提交
397
        if (!Kext->Enabled || Kext->PlistDataSize == 0) {
398 399 400
          continue;
        }

401
        BundleName  = OC_BLOB_GET (&Kext->BundleName);
402 403
        MatchKernel = OC_BLOB_GET (&Kext->MatchKernel);

404
        if (AsciiStrnCmp (DarwinVersion, MatchKernel, AsciiStrLen (MatchKernel)) != 0) {
405 406 407 408 409 410 411 412
          DEBUG ((
            DEBUG_INFO,
            "OC: Prelink injection skips %a kext at %u due to version %a vs %a",
            BundleName,
            Index,
            MatchKernel,
            DarwinVersion
            ));
V
vit9696 已提交
413 414 415 416
          continue;
        }

        AsciiSPrint (FullPath, sizeof (FullPath), "/Library/Extensions/%a", BundleName);
417 418
        if (Kext->ImageData != NULL) {
          ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
419 420 421 422 423 424 425
        } else {
          ExecutablePath = NULL;
        }

        Status = PrelinkedInjectKext (
          &Context,
          FullPath,
426 427
          Kext->PlistData,
          Kext->PlistDataSize,
V
vit9696 已提交
428
          ExecutablePath,
429 430
          Kext->ImageData,
          Kext->ImageDataSize
V
vit9696 已提交
431 432
          );

433 434 435 436 437 438
        DEBUG ((
          EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
          "OC: Prelink injection %a - %r\n",
          BundleName,
          Status
          ));
V
vit9696 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
      }

      Status = PrelinkedInjectComplete (&Context);
      if (EFI_ERROR (Status)) {
        DEBUG ((DEBUG_WARN, "OC: Prelink insertion error - %r\n", Status));
      }
    } else {
      DEBUG ((DEBUG_WARN, "OC: Prelink inject prepare error - %r\n", Status));
    }

    *KernelSize = Context.PrelinkedSize;

    PrelinkedContextFree (&Context);
  }

  return Status;
}

STATIC
EFI_STATUS
EFIAPI
OcKernelFileOpen (
  IN  EFI_FILE_PROTOCOL       *This,
  OUT EFI_FILE_PROTOCOL       **NewHandle,
  IN  CHAR16                  *FileName,
  IN  UINT64                  OpenMode,
  IN  UINT64                  Attributes
  )
{
  EFI_STATUS         Status;
  UINT8              *Kernel;
  UINT32             KernelSize;
  UINT32             AllocatedSize;
  CHAR16             *FileNameCopy;
  EFI_FILE_PROTOCOL  *VirtualFileHandle;
  EFI_STATUS         PrelinkedStatus;
  EFI_TIME           ModificationTime;
476
  CHAR8              DarwinVersion[16];
V
vit9696 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

  Status = This->Open (This, NewHandle, FileName, OpenMode, Attributes);

  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // boot.efi uses /S/L/K/kernel as is to determine valid filesystem.
  // Just skip it to speedup the boot process.
  // On 10.9 mach_kernel is loaded for manual linking aferwards, so we cannot skip it.
  //
  if (OpenMode == EFI_FILE_MODE_READ
    && StrStr (FileName, L"kernel") != NULL
    && StrCmp (FileName, L"System\\Library\\Kernels\\kernel") != 0) {

    DEBUG ((DEBUG_INFO, "Trying XNU hook on %s\n", FileName));
    Status = ReadAppleKernel (
      *NewHandle,
      &Kernel,
      &KernelSize,
      &AllocatedSize,
      OcKernelLoadKextsAndReserve (mOcStorage, mOcConfiguration)
      );
    DEBUG ((DEBUG_INFO, "Result of XNU hook on %s is %r\n", FileName, Status));

    //
    // This is not Apple kernel, just return the original file.
    //
    if (!EFI_ERROR (Status)) {
507 508
      OcKernelReadDarwinVersion (Kernel, KernelSize, DarwinVersion, sizeof (DarwinVersion));
      OcKernelApplyPatches (mOcConfiguration, DarwinVersion, NULL, Kernel, KernelSize);
V
vit9696 已提交
509 510 511

      PrelinkedStatus = OcKernelProcessPrelinked (
        mOcConfiguration,
512
        DarwinVersion,
V
vit9696 已提交
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
        Kernel,
        &KernelSize,
        AllocatedSize
        );

      DEBUG ((DEBUG_INFO, "Prelinked status - %r\n", PrelinkedStatus));

      Status = GetFileModifcationTime (*NewHandle, &ModificationTime);
      if (EFI_ERROR (Status)) {
        ZeroMem (&ModificationTime, sizeof (ModificationTime));
      }

      (*NewHandle)->Close(*NewHandle);

      //
      // This was our file, yet firmware is dying.
      //
      FileNameCopy = AllocateCopyPool (StrSize (FileName), FileName);
      if (FileNameCopy == NULL) {
        DEBUG ((DEBUG_WARN, "Failed to allocate kernel name (%a) copy\n", FileName));
        FreePool (Kernel);
        return EFI_OUT_OF_RESOURCES;
      }

      Status = CreateVirtualFile (FileNameCopy, Kernel, KernelSize, &ModificationTime, &VirtualFileHandle);
      if (EFI_ERROR (Status)) {
        DEBUG ((DEBUG_WARN, "Failed to virtualise kernel file (%a)\n", FileName));
        FreePool (Kernel);
        FreePool (FileNameCopy);
        return EFI_OUT_OF_RESOURCES;
      }

      //
      // Return our handle.
      //
      *NewHandle = VirtualFileHandle;
      return EFI_SUCCESS;
    }
  }

  return CreateRealFile (*NewHandle, NULL, TRUE, NewHandle);
}

VOID
OcLoadKernelSupport (
  IN OC_STORAGE_CONTEXT  *Storage,
  IN OC_GLOBAL_CONFIG    *Config
  )
{
  EFI_STATUS  Status;

  Status = EnableVirtualFs (gBS, OcKernelFileOpen);

  if (!EFI_ERROR (Status)) {
    mOcStorage       = Storage;
    mOcConfiguration = Config;
  } else {
    DEBUG ((DEBUG_ERROR, "OC: Failed to enable vfs - %r\n", Status));
  }
}

VOID
OcUnloadKernelSupport (
  VOID
  )
{
  EFI_STATUS  Status;

  if (mOcStorage != NULL) {
    Status = DisableVirtualFs (gBS);
    if (EFI_ERROR (Status)) {
      DEBUG ((DEBUG_ERROR, "OC: Failed to disable vfs - %r\n", Status));
    }
    mOcStorage       = NULL;
    mOcConfiguration = NULL;
  }
}