OpenCoreKernel.c 19.4 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
#include <Library/OcVirtualFsLib.h>
#include <Library/PrintLib.h>
#include <Library/UefiBootServicesTableLib.h>

STATIC OC_STORAGE_CONTEXT  *mOcStorage;
STATIC OC_GLOBAL_CONFIG    *mOcConfiguration;
29
STATIC OC_CPU_INFO         *mOcCpuInfo;
V
vit9696 已提交
30

31
STATIC
32 33 34 35 36 37
UINT32
OcParseDarwinVersion (
  IN  CONST CHAR8         *String
  )
{
  UINT32  Version;
38
  UINT32  VersionPart;
39 40 41 42 43 44 45 46 47 48
  UINT32  Index;
  UINT32  Index2;

  if (*String == '\0' || *String < '0' || *String > '9') {
    return 0;
  }

  Version = 0;

  for (Index = 0; Index < 3; ++Index) {
49 50 51 52
    Version *= 100;

    VersionPart = 0;

53
    for (Index2 = 0; Index2 < 2; ++Index2) {
54 55 56 57 58 59 60
      //
      // Handle single digit parts, i.e. parse 1.2.3 as 010203.
      //
      if (*String != '.' && *String != '\0') {
        VersionPart *= 10;
      }

61
      if (*String >= '0' && *String <= '9') {
62
        VersionPart += *String++ - '0';
63 64 65 66 67
      } else if (*String != '.' && *String != '\0') {
        return 0;
      }
    }

68 69
    Version += VersionPart;

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    if (*String == '.') {
      ++String;
    }
  }

  return Version;
}

STATIC
BOOLEAN
OcMatchDarwinVersion (
  IN  UINT32  CurrentVersion,
  IN  UINT32  MinVersion,
  IN  UINT32  MaxVersion
  )
{
  //
  // Check against min <= curr <= max.
  // curr=0 -> curr=inf, max=0  -> max=inf
  //

  //
  // Replace max inf with max known version.
  //
  if (MaxVersion == 0) {
    MaxVersion = CurrentVersion;
  }

  //
  // Handle curr=inf <= max=inf(?) case.
  //
  if (CurrentVersion == 0) {
    return MaxVersion == 0;
  }

  //
  // Handle curr=num > max=num case.
  //
  if (CurrentVersion > MaxVersion) {
    return FALSE;
  }

  //
  // Handle min=num > curr=num case.
  //
  if (CurrentVersion < MinVersion) {
    return FALSE;
  }

  return TRUE;
}

STATIC
UINT32
124 125
OcKernelReadDarwinVersion (
  IN  CONST UINT8   *Kernel,
126
  IN  UINT32        KernelSize
127 128 129 130
  )
{
  INT32   Offset;
  UINT32  Index;
131
  CHAR8   DarwinVersion[32];
132
  UINT32  DarwinVersionInteger;
133 134 135 136 137 138 139 140 141 142 143 144 145


  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"));
146
    return 0;
147 148
  }

149 150
  Offset += L_STR_LEN ("Darwin Kernel Version ");

151
  for (Index = 0; Index < ARRAY_SIZE (DarwinVersion) - 1; ++Index, ++Offset) {
152
    if ((UINT32) Offset >= KernelSize || Kernel[Offset] == ':') {
153 154 155 156 157
      break;
    }
    DarwinVersion[Index] = (CHAR8) Kernel[Offset];
  }
  DarwinVersion[Index] = '\0';
158
  DarwinVersionInteger = OcParseDarwinVersion (DarwinVersion);
159 160 161 162 163 164 165

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

167
  return DarwinVersionInteger;
168 169
}

V
vit9696 已提交
170 171 172 173 174 175 176
STATIC
UINT32
OcKernelLoadKextsAndReserve (
  IN OC_STORAGE_CONTEXT  *Storage,
  IN OC_GLOBAL_CONFIG    *Config
  )
{
V
vit9696 已提交
177 178
  UINT32               Index;
  UINT32               ReserveSize;
179
  CHAR8                *BundlePath;
180
  CHAR8                *Comment;
V
vit9696 已提交
181 182 183 184
  CHAR8                *PlistPath;
  CHAR8                *ExecutablePath;
  CHAR16               FullPath[128];
  OC_KERNEL_ADD_ENTRY  *Kext;
V
vit9696 已提交
185 186 187 188

  ReserveSize = PRELINK_INFO_RESERVE_SIZE;

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

V
vit9696 已提交
191
    if (!Kext->Enabled) {
V
vit9696 已提交
192 193 194
      continue;
    }

V
vit9696 已提交
195
    if (Kext->PlistDataSize == 0) {
196
      BundlePath     = OC_BLOB_GET (&Kext->BundlePath);
197
      Comment        = OC_BLOB_GET (&Kext->Comment);
V
vit9696 已提交
198
      PlistPath      = OC_BLOB_GET (&Kext->PlistPath);
199
      if (BundlePath[0] == '\0' || PlistPath[0] == '\0') {
V
vit9696 已提交
200
        DEBUG ((DEBUG_ERROR, "OC: Your config has improper for kext info\n"));
V
vit9696 已提交
201
        Kext->Enabled = FALSE;
V
vit9696 已提交
202 203 204 205 206 207 208
        continue;
      }

      UnicodeSPrint (
        FullPath,
        sizeof (FullPath),
        OPEN_CORE_KEXT_PATH "%a\\%a",
209
        BundlePath,
V
vit9696 已提交
210 211 212
        PlistPath
        );

V
vit9696 已提交
213 214 215
      UnicodeUefiSlashes (FullPath);

      Kext->PlistData = OcStorageReadFileUnicode (
V
vit9696 已提交
216 217
        Storage,
        FullPath,
V
vit9696 已提交
218
        &Kext->PlistDataSize
V
vit9696 已提交
219 220
        );

V
vit9696 已提交
221
      if (Kext->PlistData == NULL) {
222 223 224 225 226 227 228
        DEBUG ((
          DEBUG_ERROR,
          "OC: Plist %s is missing for kext %a (%a)\n",
          FullPath,
          BundlePath,
          Comment
          ));
V
vit9696 已提交
229
        Kext->Enabled = FALSE;
V
vit9696 已提交
230 231 232
        continue;
      }

V
vit9696 已提交
233
      ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
234 235 236 237 238
      if (ExecutablePath[0] != '\0') {
        UnicodeSPrint (
          FullPath,
          sizeof (FullPath),
          OPEN_CORE_KEXT_PATH "%a\\%a",
239
          BundlePath,
V
vit9696 已提交
240 241 242
          ExecutablePath
          );

V
vit9696 已提交
243 244 245
        UnicodeUefiSlashes (FullPath);

        Kext->ImageData = OcStorageReadFileUnicode (
V
vit9696 已提交
246 247
          Storage,
          FullPath,
V
vit9696 已提交
248
          &Kext->ImageDataSize
V
vit9696 已提交
249 250
          );

V
vit9696 已提交
251
        if (Kext->ImageData == NULL) {
252 253 254 255 256 257 258
          DEBUG ((
            DEBUG_ERROR,
            "OC: Image %s is missing for kext %a (%a)\n",
            FullPath,
            BundlePath,
            Comment
            ));
V
vit9696 已提交
259 260
          Kext->Enabled = FALSE;
          continue;
V
vit9696 已提交
261 262 263 264 265 266
        }
      }
    }

    PrelinkedReserveKextSize (
      &ReserveSize,
V
vit9696 已提交
267 268 269
      Kext->PlistDataSize,
      Kext->ImageData,
      Kext->ImageDataSize
V
vit9696 已提交
270 271 272 273 274 275 276 277
      );
  }

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

  return ReserveSize;
}

V
vit9696 已提交
278 279 280 281
STATIC
VOID
OcKernelApplyPatches (
  IN     OC_GLOBAL_CONFIG  *Config,
282
  IN     UINT32            DarwinVersion,
V
vit9696 已提交
283 284 285 286 287 288 289 290 291 292 293
  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;
294 295 296
  CONST CHAR8            *Comment;
  UINT32                 MaxKernel;
  UINT32                 MinKernel;
V
vit9696 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  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;
    }
  }

316
  for (Index = 0; Index < Config->Kernel.Patch.Count; ++Index) {
V
vit9696 已提交
317 318
    UserPatch = Config->Kernel.Patch.Values[Index];
    Target    = OC_BLOB_GET (&UserPatch->Identifier);
319
    Comment   = OC_BLOB_GET (&UserPatch->Comment);
V
vit9696 已提交
320

321
    if (!UserPatch->Enabled || (AsciiStrCmp (Target, "kernel") == 0) != IsKernelPatch) {
V
vit9696 已提交
322 323 324
      continue;
    }

325
    MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&UserPatch->MaxKernel));
326
    MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&UserPatch->MinKernel));
327

328
    if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
329 330
      DEBUG ((
        DEBUG_INFO,
331
        "OC: Kernel patcher skips %a (%a) patch at %u due to version %u <= %u <= %u\n",
332
        Target,
333
        Comment,
334
        Index,
335 336 337
        MinKernel,
        DarwinVersion,
        MaxKernel
338 339 340 341
        ));
      continue;
    }

V
vit9696 已提交
342 343 344 345 346 347 348 349
    if (!IsKernelPatch) {
      Status = PatcherInitContextFromPrelinked (
        &Patcher,
        Context,
        Target
        );

      if (EFI_ERROR (Status)) {
350
        DEBUG ((DEBUG_WARN, "OC: Kernel patcher %a (%a) init failure - %r\n", Target, Comment, Status));
351
        continue;
352
      } else {
353
        DEBUG ((DEBUG_INFO, "OC: Kernel patcher %a (%a) init succeed\n", Target, Comment));
V
vit9696 已提交
354 355 356 357 358 359 360 361 362 363 364
      }
    }

    //
    // 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
365
      || (OC_BLOB_GET (&UserPatch->Base)[0] == '\0' && UserPatch->Find.Size != UserPatch->Replace.Size)
V
vit9696 已提交
366 367
      || (UserPatch->Mask.Size > 0 && UserPatch->Find.Size != UserPatch->Mask.Size)
      || (UserPatch->ReplaceMask.Size > 0 && UserPatch->Find.Size != UserPatch->ReplaceMask.Size)) {
368
      DEBUG ((DEBUG_ERROR, "OC: Kernel patch %u for %a (%a) is borked\n", Index, Target, Comment));
V
vit9696 已提交
369 370 371 372 373
      continue;
    }

    ZeroMem (&Patch, sizeof (Patch));

374 375 376 377
    if (OC_BLOB_GET (&UserPatch->Comment)[0] != '\0') {
      Patch.Comment  = OC_BLOB_GET (&UserPatch->Comment);
    }

378
    if (OC_BLOB_GET (&UserPatch->Base)[0] != '\0') {
V
vit9696 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
      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);
V
vit9696 已提交
402
    DEBUG ((
403
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
404
      "OC: Kernel patcher result %u for %a (%a) - %r\n",
V
vit9696 已提交
405 406
      Index,
      Target,
407
      Comment,
V
vit9696 已提交
408 409
      Status
      ));
V
vit9696 已提交
410
  }
411 412 413

  if (!IsKernelPatch) {
    if (Config->Kernel.Quirks.AppleCpuPmCfgLock) {
414
      PatchAppleCpuPmCfgLock (Context);
415 416 417 418 419 420
    }

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

421 422
    if (Config->Kernel.Quirks.ThirdPartyDrives) {
      PatchThirdPartyDriveSupport (Context);
423 424 425 426 427
    }

    if (Config->Kernel.Quirks.XhciPortLimit) {
      PatchUsbXhciPortLimit (Context);
    }
428 429 430 431

    if (Config->Kernel.Quirks.DisableIoMapper) {
      PatchAppleIoMapperSupport (Context);
    }
432 433 434 435

    if (Config->Kernel.Quirks.CustomSmbiosGuid) {
      PatchCustomSmbiosGuid (Context);
    }
436 437 438 439
  } else {
    if (Config->Kernel.Quirks.AppleXcpmCfgLock) {
      PatchAppleXcpmCfgLock (&Patcher);
    }
440

441 442 443 444
    if (Config->Kernel.Quirks.AppleXcpmExtraMsrs) {
      PatchAppleXcpmExtraMsrs (&Patcher);
    }

445 446 447 448
    if (Config->Kernel.Quirks.AppleXcpmForceBoost) {
      PatchAppleXcpmForceBoost (&Patcher);
    }

449
    if (Config->Kernel.Quirks.PanicNoKextDump) {
450
      PatchPanicKextDump (&Patcher);
451 452
    }

453 454 455 456 457 458 459 460 461 462 463
    if (Config->Kernel.Emulate.Cpuid1Data[0] != 0
      || Config->Kernel.Emulate.Cpuid1Data[1] != 0
      || Config->Kernel.Emulate.Cpuid1Data[2] != 0
      || Config->Kernel.Emulate.Cpuid1Data[3] != 0) {
      PatchKernelCpuId (
        &Patcher,
        mOcCpuInfo,
        Config->Kernel.Emulate.Cpuid1Data,
        Config->Kernel.Emulate.Cpuid1Mask
        );
    }
V
vit9696 已提交
464 465 466 467

    if (Config->Kernel.Quirks.LapicKernelPanic) {
      PatchLapicKernelPanic (&Patcher);
    }
468 469 470 471

    if (Config->Kernel.Quirks.PowerTimeoutKernelPanic) {
      PatchPowerStateTimeout (&Patcher);
    }
472 473 474 475 476 477 478
  }
}

STATIC
VOID
OcKernelBlockKexts (
  IN     OC_GLOBAL_CONFIG  *Config,
479
  IN     UINT32            DarwinVersion,
480 481 482 483 484 485 486 487
  IN     PRELINKED_CONTEXT *Context
  )
{
  EFI_STATUS             Status;
  PATCHER_CONTEXT        Patcher;
  UINT32                 Index;
  OC_KERNEL_BLOCK_ENTRY  *Kext;
  CONST CHAR8            *Target;
488 489 490
  CONST CHAR8            *Comment;
  UINT32                 MaxKernel;
  UINT32                 MinKernel;
491 492

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

V
vit9696 已提交
497
    if (!Kext->Enabled) {
498 499 500
      continue;
    }

501
    MaxKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
502
    MinKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
503

504
    if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
505 506
      DEBUG ((
        DEBUG_INFO,
507
        "OC: Prelink blocker skips %a (%a) block at %u due to version %u <= %u <= %u\n",
508
        Target,
509
        Comment,
510
        Index,
511 512 513
        MinKernel,
        DarwinVersion,
        MaxKernel
514 515 516 517 518 519 520 521 522 523 524
        ));
      continue;
    }

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

    if (EFI_ERROR (Status)) {
525
      DEBUG ((DEBUG_WARN, "OC: Prelink blocker %a (%a) init failure - %r\n", Target, Comment, Status));
526 527 528 529
      continue;
    }

    Status = PatcherBlockKext (&Patcher);
530 531 532

    DEBUG ((
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
533
      "OC: Prelink blocker %a (%a) - %r\n",
534
      Target,
535
      Comment,
536 537
      Status
      ));
538
  }
V
vit9696 已提交
539 540
}

V
vit9696 已提交
541 542 543 544
STATIC
EFI_STATUS
OcKernelProcessPrelinked (
  IN     OC_GLOBAL_CONFIG  *Config,
545
  IN     UINT32            DarwinVersion,
V
vit9696 已提交
546 547 548 549 550
  IN OUT UINT8             *Kernel,
  IN     UINT32            *KernelSize,
  IN     UINT32            AllocatedSize
  )
{
551 552
  EFI_STATUS           Status;
  PRELINKED_CONTEXT    Context;
553
  CHAR8                *BundlePath;
554
  CHAR8                *ExecutablePath;
555
  CHAR8                *Comment;
556 557 558
  UINT32               Index;
  CHAR8                FullPath[128];
  OC_KERNEL_ADD_ENTRY  *Kext;
559 560
  UINT32               MaxKernel;
  UINT32               MinKernel;
V
vit9696 已提交
561 562 563 564

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

  if (!EFI_ERROR (Status)) {
565 566 567
    OcKernelApplyPatches (Config, DarwinVersion, &Context, NULL, 0);

    OcKernelBlockKexts (Config, DarwinVersion, &Context);
V
vit9696 已提交
568 569 570 571 572

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

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

V
vit9696 已提交
575
        if (!Kext->Enabled || Kext->PlistDataSize == 0) {
576 577 578
          continue;
        }

579
        BundlePath  = OC_BLOB_GET (&Kext->BundlePath);
580 581
        Comment     = OC_BLOB_GET (&Kext->Comment);
        MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
582
        MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
583

584
        if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
585 586
          DEBUG ((
            DEBUG_INFO,
587
            "OC: Prelink injection skips %a (%a) kext at %u due to version %u <= %u <= %u\n",
588
            BundlePath,
589
            Comment,
590
            Index,
591 592 593
            MinKernel,
            DarwinVersion,
            MaxKernel
594
            ));
V
vit9696 已提交
595 596 597
          continue;
        }

598
        AsciiSPrint (FullPath, sizeof (FullPath), "/Library/Extensions/%a", BundlePath);
599 600
        if (Kext->ImageData != NULL) {
          ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
601 602 603 604 605 606 607
        } else {
          ExecutablePath = NULL;
        }

        Status = PrelinkedInjectKext (
          &Context,
          FullPath,
608 609
          Kext->PlistData,
          Kext->PlistDataSize,
V
vit9696 已提交
610
          ExecutablePath,
611 612
          Kext->ImageData,
          Kext->ImageDataSize
V
vit9696 已提交
613 614
          );

615 616
        DEBUG ((
          EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
617
          "OC: Prelink injection %a (%a) - %r\n",
618
          BundlePath,
619
          Comment,
620 621
          Status
          ));
V
vit9696 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
      }

      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;
659
  UINT32             DarwinVersion;
V
vit9696 已提交
660 661 662

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

663 664 665 666 667 668 669 670
  DEBUG ((
    DEBUG_VERBOSE,
    "Opening file %s with %u mode gave - %r\n",
    FileName,
    (UINT32) OpenMode,
    Status
    ));

V
vit9696 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
  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)) {
698
      DarwinVersion = OcKernelReadDarwinVersion (Kernel, KernelSize);
699
      OcKernelApplyPatches (mOcConfiguration, DarwinVersion, NULL, Kernel, KernelSize);
V
vit9696 已提交
700 701 702

      PrelinkedStatus = OcKernelProcessPrelinked (
        mOcConfiguration,
703
        DarwinVersion,
V
vit9696 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        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;
    }
  }

744 745 746 747
  //
  // We recurse the filtering to additionally catch com.apple.boot.[RPS] directories.
  //
  return CreateRealFile (*NewHandle, OcKernelFileOpen, TRUE, NewHandle);
V
vit9696 已提交
748 749 750 751 752
}

VOID
OcLoadKernelSupport (
  IN OC_STORAGE_CONTEXT  *Storage,
753 754
  IN OC_GLOBAL_CONFIG    *Config,
  IN OC_CPU_INFO         *CpuInfo
V
vit9696 已提交
755 756 757 758 759 760 761 762 763
  )
{
  EFI_STATUS  Status;

  Status = EnableVirtualFs (gBS, OcKernelFileOpen);

  if (!EFI_ERROR (Status)) {
    mOcStorage       = Storage;
    mOcConfiguration = Config;
764
    mOcCpuInfo       = CpuInfo;
V
vit9696 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  } 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;
  }
}