OpenCoreKernel.c 20.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
  )
{
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.IncreasePciBarSize) {
      PatchIncreasePciBarSize (Context);     
    }

464 465 466
    if (Config->Kernel.Quirks.CustomSmbiosGuid) {
      PatchCustomSmbiosGuid (Context);
    }
467 468 469 470

    if (Config->Kernel.Quirks.DummyPowerManagement) {
      PatchDummyPowerManagement (Context);
    }
471 472 473 474
  } else {
    if (Config->Kernel.Quirks.AppleXcpmCfgLock) {
      PatchAppleXcpmCfgLock (&Patcher);
    }
475

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

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

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

488 489 490 491 492 493 494 495 496 497 498
    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 已提交
499 500 501 502

    if (Config->Kernel.Quirks.LapicKernelPanic) {
      PatchLapicKernelPanic (&Patcher);
    }
503 504 505 506

    if (Config->Kernel.Quirks.PowerTimeoutKernelPanic) {
      PatchPowerStateTimeout (&Patcher);
    }
507 508 509 510 511 512 513
  }
}

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

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

V
vit9696 已提交
532
    if (!Kext->Enabled) {
533 534 535
      continue;
    }

536
    MaxKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
537
    MinKernel = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
538

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

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

    if (EFI_ERROR (Status)) {
560
      DEBUG ((DEBUG_WARN, "OC: Prelink blocker %a (%a) init failure - %r\n", Target, Comment, Status));
561 562 563 564
      continue;
    }

    Status = PatcherBlockKext (&Patcher);
565 566 567

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

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

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

  if (!EFI_ERROR (Status)) {
600 601 602
    OcKernelApplyPatches (Config, DarwinVersion, &Context, NULL, 0);

    OcKernelBlockKexts (Config, DarwinVersion, &Context);
V
vit9696 已提交
603 604 605 606 607

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

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

V
vit9696 已提交
610
        if (!Kext->Enabled || Kext->PlistDataSize == 0) {
611 612 613
          continue;
        }

614
        BundlePath  = OC_BLOB_GET (&Kext->BundlePath);
615 616
        Comment     = OC_BLOB_GET (&Kext->Comment);
        MaxKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MaxKernel));
617
        MinKernel   = OcParseDarwinVersion (OC_BLOB_GET (&Kext->MinKernel));
618

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

633 634 635 636 637 638
        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;
        }

639 640
        if (Kext->ImageData != NULL) {
          ExecutablePath = OC_BLOB_GET (&Kext->ExecutablePath);
V
vit9696 已提交
641 642 643 644 645 646 647
        } else {
          ExecutablePath = NULL;
        }

        Status = PrelinkedInjectKext (
          &Context,
          FullPath,
648 649
          Kext->PlistData,
          Kext->PlistDataSize,
V
vit9696 已提交
650
          ExecutablePath,
651 652
          Kext->ImageData,
          Kext->ImageDataSize
V
vit9696 已提交
653 654
          );

655 656
        DEBUG ((
          EFI_ERROR (Status) ? DEBUG_WARN : DEBUG_INFO,
657
          "OC: Prelink injection %a (%a) - %r\n",
658
          BundlePath,
659
          Comment,
660 661
          Status
          ));
V
vit9696 已提交
662 663 664 665 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
      }

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

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

703 704 705 706 707 708 709 710
  DEBUG ((
    DEBUG_VERBOSE,
    "Opening file %s with %u mode gave - %r\n",
    FileName,
    (UINT32) OpenMode,
    Status
    ));

V
vit9696 已提交
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
  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)) {
738
      DarwinVersion = OcKernelReadDarwinVersion (Kernel, KernelSize);
739
      OcKernelApplyPatches (mOcConfiguration, DarwinVersion, NULL, Kernel, KernelSize);
V
vit9696 已提交
740 741 742

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

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

VOID
OcLoadKernelSupport (
  IN OC_STORAGE_CONTEXT  *Storage,
793 794
  IN OC_GLOBAL_CONFIG    *Config,
  IN OC_CPU_INFO         *CpuInfo
V
vit9696 已提交
795 796 797 798 799 800 801 802 803
  )
{
  EFI_STATUS  Status;

  Status = EnableVirtualFs (gBS, OcKernelFileOpen);

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