OpenCoreKernel.c 20.7 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
  )
{
177
  EFI_STATUS           Status;
V
vit9696 已提交
178 179
  UINT32               Index;
  UINT32               ReserveSize;
180
  CHAR8                *BundlePath;
181
  CHAR8                *Comment;
V
vit9696 已提交
182 183
  CHAR8                *PlistPath;
  CHAR8                *ExecutablePath;
184
  CHAR16               FullPath[OC_STORAGE_SAFE_PATH_MAX];
V
vit9696 已提交
185
  OC_KERNEL_ADD_ENTRY  *Kext;
V
vit9696 已提交
186 187 188 189

  ReserveSize = PRELINK_INFO_RESERVE_SIZE;

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

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

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

206
      Status = OcUnicodeSafeSPrint (
V
vit9696 已提交
207 208 209
        FullPath,
        sizeof (FullPath),
        OPEN_CORE_KEXT_PATH "%a\\%a",
210
        BundlePath,
V
vit9696 已提交
211 212
        PlistPath
        );
213 214 215 216 217 218 219 220 221 222 223
      if (EFI_ERROR (Status)) {
        DEBUG ((
          DEBUG_WARN,
          "OC: Failed to fit kext path %s%a\\%a",
          OPEN_CORE_KEXT_PATH,
          BundlePath,
          PlistPath
          ));
        Kext->Enabled = FALSE;
        continue;
      }
V
vit9696 已提交
224

V
vit9696 已提交
225 226 227
      UnicodeUefiSlashes (FullPath);

      Kext->PlistData = OcStorageReadFileUnicode (
V
vit9696 已提交
228 229
        Storage,
        FullPath,
V
vit9696 已提交
230
        &Kext->PlistDataSize
V
vit9696 已提交
231 232
        );

V
vit9696 已提交
233
      if (Kext->PlistData == NULL) {
234 235 236 237 238 239 240
        DEBUG ((
          DEBUG_ERROR,
          "OC: Plist %s is missing for kext %a (%a)\n",
          FullPath,
          BundlePath,
          Comment
          ));
V
vit9696 已提交
241
        Kext->Enabled = FALSE;
V
vit9696 已提交
242 243 244
        continue;
      }

V
vit9696 已提交
245
      ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
246
      if (ExecutablePath[0] != '\0') {
247
        Status = OcUnicodeSafeSPrint (
V
vit9696 已提交
248 249 250
          FullPath,
          sizeof (FullPath),
          OPEN_CORE_KEXT_PATH "%a\\%a",
251
          BundlePath,
V
vit9696 已提交
252 253
          ExecutablePath
          );
254 255 256 257 258 259 260 261 262 263 264 265 266
        if (EFI_ERROR (Status)) {
          DEBUG ((
            DEBUG_WARN,
            "OC: Failed to fit kext path %s%a\\%a",
            OPEN_CORE_KEXT_PATH,
            BundlePath,
            ExecutablePath
            ));
          Kext->Enabled = FALSE;
          FreePool (Kext->PlistData);
          Kext->PlistData = NULL;
          continue;
        }
V
vit9696 已提交
267

V
vit9696 已提交
268 269 270
        UnicodeUefiSlashes (FullPath);

        Kext->ImageData = OcStorageReadFileUnicode (
V
vit9696 已提交
271 272
          Storage,
          FullPath,
V
vit9696 已提交
273
          &Kext->ImageDataSize
V
vit9696 已提交
274 275
          );

V
vit9696 已提交
276
        if (Kext->ImageData == NULL) {
277 278 279 280 281 282 283
          DEBUG ((
            DEBUG_ERROR,
            "OC: Image %s is missing for kext %a (%a)\n",
            FullPath,
            BundlePath,
            Comment
            ));
V
vit9696 已提交
284
          Kext->Enabled = FALSE;
285 286
          FreePool (Kext->PlistData);
          Kext->PlistData = NULL;
V
vit9696 已提交
287
          continue;
V
vit9696 已提交
288 289 290 291 292 293
        }
      }
    }

    PrelinkedReserveKextSize (
      &ReserveSize,
V
vit9696 已提交
294 295 296
      Kext->PlistDataSize,
      Kext->ImageData,
      Kext->ImageDataSize
V
vit9696 已提交
297 298 299 300 301 302 303 304
      );
  }

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

  return ReserveSize;
}

V
vit9696 已提交
305 306 307 308
STATIC
VOID
OcKernelApplyPatches (
  IN     OC_GLOBAL_CONFIG  *Config,
309
  IN     UINT32            DarwinVersion,
V
vit9696 已提交
310 311 312 313 314 315 316 317 318 319 320
  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;
321 322 323
  CONST CHAR8            *Comment;
  UINT32                 MaxKernel;
  UINT32                 MinKernel;
V
vit9696 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  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;
    }
  }

343
  for (Index = 0; Index < Config->Kernel.Patch.Count; ++Index) {
V
vit9696 已提交
344 345
    UserPatch = Config->Kernel.Patch.Values[Index];
    Target    = OC_BLOB_GET (&UserPatch->Identifier);
346
    Comment   = OC_BLOB_GET (&UserPatch->Comment);
V
vit9696 已提交
347

348
    if (!UserPatch->Enabled || (AsciiStrCmp (Target, "kernel") == 0) != IsKernelPatch) {
V
vit9696 已提交
349 350 351
      continue;
    }

352
    MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&UserPatch->MaxKernel));
353
    MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&UserPatch->MinKernel));
354

355
    if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
356 357
      DEBUG ((
        DEBUG_INFO,
358
        "OC: Kernel patcher skips %a (%a) patch at %u due to version %u <= %u <= %u\n",
359
        Target,
360
        Comment,
361
        Index,
362 363 364
        MinKernel,
        DarwinVersion,
        MaxKernel
365 366 367 368
        ));
      continue;
    }

V
vit9696 已提交
369 370 371 372 373 374 375 376
    if (!IsKernelPatch) {
      Status = PatcherInitContextFromPrelinked (
        &Patcher,
        Context,
        Target
        );

      if (EFI_ERROR (Status)) {
377
        DEBUG ((DEBUG_WARN, "OC: Kernel patcher %a (%a) init failure - %r\n", Target, Comment, Status));
378
        continue;
379
      } else {
380
        DEBUG ((DEBUG_INFO, "OC: Kernel patcher %a (%a) init succeed\n", Target, Comment));
V
vit9696 已提交
381 382 383 384 385 386 387 388 389 390 391
      }
    }

    //
    // 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
392
      || (OC_BLOB_GET (&UserPatch->Base)[0] == '\0' && UserPatch->Find.Size != UserPatch->Replace.Size)
V
vit9696 已提交
393 394
      || (UserPatch->Mask.Size > 0 && UserPatch->Find.Size != UserPatch->Mask.Size)
      || (UserPatch->ReplaceMask.Size > 0 && UserPatch->Find.Size != UserPatch->ReplaceMask.Size)) {
395
      DEBUG ((DEBUG_ERROR, "OC: Kernel patch %u for %a (%a) is borked\n", Index, Target, Comment));
V
vit9696 已提交
396 397 398 399 400
      continue;
    }

    ZeroMem (&Patch, sizeof (Patch));

401 402 403 404
    if (OC_BLOB_GET (&UserPatch->Comment)[0] != '\0') {
      Patch.Comment  = OC_BLOB_GET (&UserPatch->Comment);
    }

405
    if (OC_BLOB_GET (&UserPatch->Base)[0] != '\0') {
V
vit9696 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
      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 已提交
429
    DEBUG ((
430
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
431
      "OC: Kernel patcher result %u for %a (%a) - %r\n",
V
vit9696 已提交
432 433
      Index,
      Target,
434
      Comment,
V
vit9696 已提交
435 436
      Status
      ));
V
vit9696 已提交
437
  }
438 439 440

  if (!IsKernelPatch) {
    if (Config->Kernel.Quirks.AppleCpuPmCfgLock) {
441
      PatchAppleCpuPmCfgLock (Context);
442 443 444 445 446 447
    }

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

448 449
    if (Config->Kernel.Quirks.ThirdPartyDrives) {
      PatchThirdPartyDriveSupport (Context);
450 451 452 453 454
    }

    if (Config->Kernel.Quirks.XhciPortLimit) {
      PatchUsbXhciPortLimit (Context);
    }
455 456 457 458

    if (Config->Kernel.Quirks.DisableIoMapper) {
      PatchAppleIoMapperSupport (Context);
    }
459

460 461 462 463
    if (Config->Kernel.Quirks.DisableRtcChecksum) {
      PatchAppleRtcChecksum (Context);
    }

464 465 466 467
    if (Config->Kernel.Quirks.IncreasePciBarSize) {
      PatchIncreasePciBarSize (Context);     
    }

468 469 470
    if (Config->Kernel.Quirks.CustomSmbiosGuid) {
      PatchCustomSmbiosGuid (Context);
    }
471 472 473 474

    if (Config->Kernel.Quirks.DummyPowerManagement) {
      PatchDummyPowerManagement (Context);
    }
475 476 477 478
  } else {
    if (Config->Kernel.Quirks.AppleXcpmCfgLock) {
      PatchAppleXcpmCfgLock (&Patcher);
    }
479

480 481 482 483
    if (Config->Kernel.Quirks.AppleXcpmExtraMsrs) {
      PatchAppleXcpmExtraMsrs (&Patcher);
    }

484 485 486 487
    if (Config->Kernel.Quirks.AppleXcpmForceBoost) {
      PatchAppleXcpmForceBoost (&Patcher);
    }

488
    if (Config->Kernel.Quirks.PanicNoKextDump) {
489
      PatchPanicKextDump (&Patcher);
490 491
    }

492 493 494 495 496 497 498 499 500 501 502
    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 已提交
503 504 505 506

    if (Config->Kernel.Quirks.LapicKernelPanic) {
      PatchLapicKernelPanic (&Patcher);
    }
507 508 509 510

    if (Config->Kernel.Quirks.PowerTimeoutKernelPanic) {
      PatchPowerStateTimeout (&Patcher);
    }
511 512 513 514 515 516 517
  }
}

STATIC
VOID
OcKernelBlockKexts (
  IN     OC_GLOBAL_CONFIG  *Config,
518
  IN     UINT32            DarwinVersion,
519 520 521 522 523 524 525 526
  IN     PRELINKED_CONTEXT *Context
  )
{
  EFI_STATUS             Status;
  PATCHER_CONTEXT        Patcher;
  UINT32                 Index;
  OC_KERNEL_BLOCK_ENTRY  *Kext;
  CONST CHAR8            *Target;
527 528 529
  CONST CHAR8            *Comment;
  UINT32                 MaxKernel;
  UINT32                 MinKernel;
530 531

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

V
vit9696 已提交
536
    if (!Kext->Enabled) {
537 538 539
      continue;
    }

540
    MaxKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
541
    MinKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
542

543
    if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
544 545
      DEBUG ((
        DEBUG_INFO,
546
        "OC: Prelink blocker skips %a (%a) block at %u due to version %u <= %u <= %u\n",
547
        Target,
548
        Comment,
549
        Index,
550 551 552
        MinKernel,
        DarwinVersion,
        MaxKernel
553 554 555 556 557 558 559 560 561 562 563
        ));
      continue;
    }

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

    if (EFI_ERROR (Status)) {
564
      DEBUG ((DEBUG_WARN, "OC: Prelink blocker %a (%a) init failure - %r\n", Target, Comment, Status));
565 566 567 568
      continue;
    }

    Status = PatcherBlockKext (&Patcher);
569 570 571

    DEBUG ((
      EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
572
      "OC: Prelink blocker %a (%a) - %r\n",
573
      Target,
574
      Comment,
575 576
      Status
      ));
577
  }
V
vit9696 已提交
578 579
}

V
vit9696 已提交
580 581 582 583
STATIC
EFI_STATUS
OcKernelProcessPrelinked (
  IN     OC_GLOBAL_CONFIG  *Config,
584
  IN     UINT32            DarwinVersion,
V
vit9696 已提交
585 586 587 588 589
  IN OUT UINT8             *Kernel,
  IN     UINT32            *KernelSize,
  IN     UINT32            AllocatedSize
  )
{
590 591
  EFI_STATUS           Status;
  PRELINKED_CONTEXT    Context;
592
  CHAR8                *BundlePath;
593
  CHAR8                *ExecutablePath;
594
  CHAR8                *Comment;
595
  UINT32               Index;
596
  CHAR8                FullPath[OC_STORAGE_SAFE_PATH_MAX];
597
  OC_KERNEL_ADD_ENTRY  *Kext;
598 599
  UINT32               MaxKernel;
  UINT32               MinKernel;
V
vit9696 已提交
600 601 602 603

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

  if (!EFI_ERROR (Status)) {
604 605 606
    OcKernelApplyPatches (Config, DarwinVersion, &Context, NULL, 0);

    OcKernelBlockKexts (Config, DarwinVersion, &Context);
V
vit9696 已提交
607 608 609 610 611

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

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

V
vit9696 已提交
614
        if (!Kext->Enabled || Kext->PlistDataSize == 0) {
615 616 617
          continue;
        }

618
        BundlePath  = OC_BLOB_GET (&Kext->BundlePath);
619 620
        Comment     = OC_BLOB_GET (&Kext->Comment);
        MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
621
        MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
622

623
        if (!OcMatchDarwinVersion (DarwinVersion, MinKernel, MaxKernel)) {
624 625
          DEBUG ((
            DEBUG_INFO,
626
            "OC: Prelink injection skips %a (%a) kext at %u due to version %u <= %u <= %u\n",
627
            BundlePath,
628
            Comment,
629
            Index,
630 631 632
            MinKernel,
            DarwinVersion,
            MaxKernel
633
            ));
V
vit9696 已提交
634 635 636
          continue;
        }

637 638 639 640 641 642
        Status = OcAsciiSafeSPrint (FullPath, sizeof (FullPath), "/Library/Extensions/%a", BundlePath);
        if (EFI_ERROR (Status)) {
          DEBUG ((DEBUG_WARN, "OC: Failed to fit kext path /Library/Extensions/%a", BundlePath));
          continue;
        }

643 644
        if (Kext->ImageData != NULL) {
          ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
645 646 647 648 649 650 651
        } else {
          ExecutablePath = NULL;
        }

        Status = PrelinkedInjectKext (
          &Context,
          FullPath,
652 653
          Kext->PlistData,
          Kext->PlistDataSize,
V
vit9696 已提交
654
          ExecutablePath,
655 656
          Kext->ImageData,
          Kext->ImageDataSize
V
vit9696 已提交
657 658
          );

659 660
        DEBUG ((
          EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
661
          "OC: Prelink injection %a (%a) - %r\n",
662
          BundlePath,
663
          Comment,
664 665
          Status
          ));
V
vit9696 已提交
666 667 668 669 670 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 698 699 700 701 702
      }

      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;
703
  UINT32             DarwinVersion;
V
vit9696 已提交
704

V
vit9696 已提交
705
  Status = SafeFileOpen (This, NewHandle, FileName, OpenMode, Attributes);
V
vit9696 已提交
706

707 708 709 710 711 712 713 714
  DEBUG ((
    DEBUG_VERBOSE,
    "Opening file %s with %u mode gave - %r\n",
    FileName,
    (UINT32) OpenMode,
    Status
    ));

V
vit9696 已提交
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
  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)) {
742
      DarwinVersion = OcKernelReadDarwinVersion (Kernel, KernelSize);
743
      OcKernelApplyPatches (mOcConfiguration, DarwinVersion, NULL, Kernel, KernelSize);
V
vit9696 已提交
744 745 746

      PrelinkedStatus = OcKernelProcessPrelinked (
        mOcConfiguration,
747
        DarwinVersion,
V
vit9696 已提交
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        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;
    }
  }

788 789 790 791
  //
  // We recurse the filtering to additionally catch com.apple.boot.[RPS] directories.
  //
  return CreateRealFile (*NewHandle, OcKernelFileOpen, TRUE, NewHandle);
V
vit9696 已提交
792 793 794 795 796
}

VOID
OcLoadKernelSupport (
  IN OC_STORAGE_CONTEXT  *Storage,
797 798
  IN OC_GLOBAL_CONFIG    *Config,
  IN OC_CPU_INFO         *CpuInfo
V
vit9696 已提交
799 800 801 802 803 804 805 806 807
  )
{
  EFI_STATUS  Status;

  Status = EnableVirtualFs (gBS, OcKernelFileOpen);

  if (!EFI_ERROR (Status)) {
    mOcStorage       = Storage;
    mOcConfiguration = Config;
808
    mOcCpuInfo       = CpuInfo;
V
vit9696 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
  } 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;
  }
}