OpenCoreKernel.c 19.6 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 436
    if (Config->Kernel.Quirks.IncreasePciBarSize) {
      PatchIncreasePciBarSize (Context);     
    }

437 438 439
    if (Config->Kernel.Quirks.CustomSmbiosGuid) {
      PatchCustomSmbiosGuid (Context);
    }
440 441 442 443

    if (Config->Kernel.Quirks.DummyPowerManagement) {
      PatchDummyPowerManagement (Context);
    }
444 445 446 447
  } else {
    if (Config->Kernel.Quirks.AppleXcpmCfgLock) {
      PatchAppleXcpmCfgLock (&Patcher);
    }
448

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

453 454 455 456
    if (Config->Kernel.Quirks.AppleXcpmForceBoost) {
      PatchAppleXcpmForceBoost (&Patcher);
    }

457
    if (Config->Kernel.Quirks.PanicNoKextDump) {
458
      PatchPanicKextDump (&Patcher);
459 460
    }

461 462 463 464 465 466 467 468 469 470 471
    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 已提交
472 473 474 475

    if (Config->Kernel.Quirks.LapicKernelPanic) {
      PatchLapicKernelPanic (&Patcher);
    }
476 477 478 479

    if (Config->Kernel.Quirks.PowerTimeoutKernelPanic) {
      PatchPowerStateTimeout (&Patcher);
    }
480 481 482 483 484 485 486
  }
}

STATIC
VOID
OcKernelBlockKexts (
  IN     OC_GLOBAL_CONFIG  *Config,
487
  IN     UINT32            DarwinVersion,
488 489 490 491 492 493 494 495
  IN     PRELINKED_CONTEXT *Context
  )
{
  EFI_STATUS             Status;
  PATCHER_CONTEXT        Patcher;
  UINT32                 Index;
  OC_KERNEL_BLOCK_ENTRY  *Kext;
  CONST CHAR8            *Target;
496 497 498
  CONST CHAR8            *Comment;
  UINT32                 MaxKernel;
  UINT32                 MinKernel;
499 500

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

V
vit9696 已提交
505
    if (!Kext->Enabled) {
506 507 508
      continue;
    }

509
    MaxKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
510
    MinKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
511

512
    if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
513 514
      DEBUG ((
        DEBUG_INFO,
515
        "OC: Prelink blocker skips %a (%a) block at %u due to version %u <= %u <= %u\n",
516
        Target,
517
        Comment,
518
        Index,
519 520 521
        MinKernel,
        DarwinVersion,
        MaxKernel
522 523 524 525 526 527 528 529 530 531 532
        ));
      continue;
    }

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

    if (EFI_ERROR (Status)) {
533
      DEBUG ((DEBUG_WARN, "OC: Prelink blocker %a (%a) init failure - %r\n", Target, Comment, Status));
534 535 536 537
      continue;
    }

    Status = PatcherBlockKext (&Patcher);
538 539 540

    DEBUG ((
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
541
      "OC: Prelink blocker %a (%a) - %r\n",
542
      Target,
543
      Comment,
544 545
      Status
      ));
546
  }
V
vit9696 已提交
547 548
}

V
vit9696 已提交
549 550 551 552
STATIC
EFI_STATUS
OcKernelProcessPrelinked (
  IN     OC_GLOBAL_CONFIG  *Config,
553
  IN     UINT32            DarwinVersion,
V
vit9696 已提交
554 555 556 557 558
  IN OUT UINT8             *Kernel,
  IN     UINT32            *KernelSize,
  IN     UINT32            AllocatedSize
  )
{
559 560
  EFI_STATUS           Status;
  PRELINKED_CONTEXT    Context;
561
  CHAR8                *BundlePath;
562
  CHAR8                *ExecutablePath;
563
  CHAR8                *Comment;
564 565 566
  UINT32               Index;
  CHAR8                FullPath[128];
  OC_KERNEL_ADD_ENTRY  *Kext;
567 568
  UINT32               MaxKernel;
  UINT32               MinKernel;
V
vit9696 已提交
569 570 571 572

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

  if (!EFI_ERROR (Status)) {
573 574 575
    OcKernelApplyPatches (Config, DarwinVersion, &Context, NULL, 0);

    OcKernelBlockKexts (Config, DarwinVersion, &Context);
V
vit9696 已提交
576 577 578 579 580

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

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

V
vit9696 已提交
583
        if (!Kext->Enabled || Kext->PlistDataSize == 0) {
584 585 586
          continue;
        }

587
        BundlePath  = OC_BLOB_GET (&Kext->BundlePath);
588 589
        Comment     = OC_BLOB_GET (&Kext->Comment);
        MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
590
        MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
591

592
        if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
593 594
          DEBUG ((
            DEBUG_INFO,
595
            "OC: Prelink injection skips %a (%a) kext at %u due to version %u <= %u <= %u\n",
596
            BundlePath,
597
            Comment,
598
            Index,
599 600 601
            MinKernel,
            DarwinVersion,
            MaxKernel
602
            ));
V
vit9696 已提交
603 604 605
          continue;
        }

606
        AsciiSPrint (FullPath, sizeof (FullPath), "/Library/Extensions/%a", BundlePath);
607 608
        if (Kext->ImageData != NULL) {
          ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
609 610 611 612 613 614 615
        } else {
          ExecutablePath = NULL;
        }

        Status = PrelinkedInjectKext (
          &Context,
          FullPath,
616 617
          Kext->PlistData,
          Kext->PlistDataSize,
V
vit9696 已提交
618
          ExecutablePath,
619 620
          Kext->ImageData,
          Kext->ImageDataSize
V
vit9696 已提交
621 622
          );

623 624
        DEBUG ((
          EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
625
          "OC: Prelink injection %a (%a) - %r\n",
626
          BundlePath,
627
          Comment,
628 629
          Status
          ));
V
vit9696 已提交
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 659 660 661 662 663 664 665 666
      }

      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;
667
  UINT32             DarwinVersion;
V
vit9696 已提交
668 669 670

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

671 672 673 674 675 676 677 678
  DEBUG ((
    DEBUG_VERBOSE,
    "Opening file %s with %u mode gave - %r\n",
    FileName,
    (UINT32) OpenMode,
    Status
    ));

V
vit9696 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
  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)) {
706
      DarwinVersion = OcKernelReadDarwinVersion (Kernel, KernelSize);
707
      OcKernelApplyPatches (mOcConfiguration, DarwinVersion, NULL, Kernel, KernelSize);
V
vit9696 已提交
708 709 710

      PrelinkedStatus = OcKernelProcessPrelinked (
        mOcConfiguration,
711
        DarwinVersion,
V
vit9696 已提交
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 744 745 746 747 748 749 750 751
        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;
    }
  }

752 753 754 755
  //
  // We recurse the filtering to additionally catch com.apple.boot.[RPS] directories.
  //
  return CreateRealFile (*NewHandle, OcKernelFileOpen, TRUE, NewHandle);
V
vit9696 已提交
756 757 758 759 760
}

VOID
OcLoadKernelSupport (
  IN OC_STORAGE_CONTEXT  *Storage,
761 762
  IN OC_GLOBAL_CONFIG    *Config,
  IN OC_CPU_INFO         *CpuInfo
V
vit9696 已提交
763 764 765 766 767 768 769 770 771
  )
{
  EFI_STATUS  Status;

  Status = EnableVirtualFs (gBS, OcKernelFileOpen);

  if (!EFI_ERROR (Status)) {
    mOcStorage       = Storage;
    mOcConfiguration = Config;
772
    mOcCpuInfo       = CpuInfo;
V
vit9696 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
  } 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;
  }
}